HexTechie
A web for devs from 0 to F

Factory Design Pattern

Factory design pattern example in Java.
-- By Jan
February 19, 2022
article image
UML diagram.

Factory design pattern is a simple and basic pattern that belongs to creational design patterns. This pattern provides an abstraction for creating objects of a specific type. To create new instances of some type, a factory is used with some arguments provided, hence the name factory pattern. Let's dive into a simple example created in Java.

First of all, we need to have an interface that specifies some basic logic our classes must implement. For that, we created a Vehicle interface with a simple method returning a String representing its name.

Vehicle.java

Next we need some implementations of that Vehicle, e.g. Car, Truck and Bus.

Car.java
Truck.java
Bus.java

Finally, let's create our factory that contains creation logic for our vehicles.

VehicleFactory.java

To create an instance of some Vehicle, we can use createVehicle static method inside our factory, which handles creation logic of all our vehicles. It's also abstracted as it returns a Vehicle and not a concrete type. A sample logic is provided in the next code.

App.java

Conclusion

That's it! We created and implemented an example of factory pattern in Java. Java standard library contains many implementations of this pattern, e.g. java.util.Calendar, which provides four getInstance static methods with different parameters to create an instance of a Calendar.