1. Overview
In this tutorial, weβll explain the factory design pattern in Java. Weβll describe two patterns, both of which are creational design patterns: Factory Method and Abstract Factory. Then weβll use an example to illustrate the patterns.
2. Factory Method Pattern
First, weβll need to define an example. Weβre working on an app for a vehicle manufacturer. Initially, we only had a client. This client built vehicles with a fuel-only engine. So to follow the single responsibility principle (SRP) and the open-close principle (OCP), weβll use the factory method design pattern.
Before we jump into the code, weβll define a default UML diagram for this pattern:
π Factory Method Pattern DefaultUsing the above UML diagram as a reference, weβll define some main concepts related to this pattern. The factory method pattern loosens the coupling code by separating our Productβs construction code from the code that uses this Product. This design makes it easy to extract the Product construction independently from the rest of the application. Besides, it allows the introduction of new products without breaking existing code.
Now letβs jump into the code. First, in our example application, weβll define the MotorVehicle interface. This interface only has one method, build(). This method is used to build a specific motor vehicle. The interfaceβs code snippet:
public interface MotorVehicle {
void build();
}
The next step is to implement the concrete classes that implement the MotorVehicle interface. Weβll create two types: Motorcycle and Car. The code for the first one is:
public class Motorcycle implements MotorVehicle {
@Override
public void build() {
System.out.println("Build Motorcycle");
}
}
In the case of the Car class, the code is:
public class Car implements MotorVehicle {
@Override
public void build() {
System.out.println("Build Car");
}
}
Then weβll create the MotorVehicleFactory class. This class is responsible for creating every new vehicle instance. Itβs an abstract class because it makes a specific vehicle for its particular factory. The code for this class is:
public abstract class MotorVehicleFactory {
public MotorVehicle create() {
MotorVehicle vehicle = createMotorVehicle();
vehicle.build();
return vehicle;
}
protected abstract MotorVehicle createMotorVehicle();
}
As we can see, the method create() calls to the abstract method createMotorVehicle() to create a specific type of motor vehicle. Thatβs why each particular motor vehicle factory must implement its correct MotorVehicle type. Previously, we implemented two MotorVehicle types: Motorcycle and Car. Now weβll extend from our base class MotorVehicleFactory to implement both.
First, the MotorcycleFactory class:
public class MotorcycleFactory extends MotorVehicleFactory {
@Override
protected MotorVehicle createMotorVehicle() {
return new Motorcycle();
}
}
Then the CarFactory class:
public class CarFactory extends MotorVehicleFactory {
@Override
protected MotorVehicle createMotorVehicle() {
return new Car();
}
}
Thatβs all; our app is designed using the factory method pattern. We can now add as many new motor vehicles as we want. Finally, we need to see how our final design looks using UML notation:
π Factory Method Pattern Result3. Abstract Factory Pattern
After our first app iteration, two new vehicle brand companies are interested in our system: NextGen and FutureVehicle. These new companies build not only fuel-only vehicles, but also electric vehicles. Each company has its vehicle design.
Our current system isnβt ready to address these new scenarios. We must support electric vehicles and consider that each company has its design. To resolve these problems, we can use the Abstract Factory Pattern. This pattern is commonly used when we start using the Factory Method Pattern, and we need to evolve our system to a more complex system. It centralizes the product creation code in one place. The UML representation is:
π Abstract Factory Pattern DefaultWe already have the MotorVehicle interface. Additionally, we must add an interface to represent electric vehicles. The code snippet for the new interface is:
public interface ElectricVehicle {
void build();
}
Next, weβll create our abstract factory. The new class is abstract because the responsibility of object creation will be for our concrete factory. This behavior follows the OCP and SRP. Letβs jump into class definition:
public abstract class Corporation {
public abstract MotorVehicle createMotorVehicle();
public abstract ElectricVehicle createElectricVehicle();
}
Before we create the concrete factory for each company, we must implement some vehicles for our new companies. Letβs make some new classes for the FutureVehicle company:
public class FutureVehicleMotorcycle implements MotorVehicle {
@Override
public void build() {
System.out.println("Future Vehicle Motorcycle");
}
}
Then the electric car instance:
public class FutureVehicleElectricCar implements ElectricVehicle {
@Override
public void build() {
System.out.println("Future Vehicle Electric Car");
}
}
Weβll do the same for the NexGen company:
public class NextGenMotorcycle implements MotorVehicle {
@Override
public void build() {
System.out.println("NextGen Motorcycle");
}
}
Additionally, the other electric car concrete implementation:
public class NextGenElectricCar implements ElectricVehicle {
@Override
public void build() {
System.out.println("NextGen Electric Car");
}
}
Finally, weβre ready to build our concrete factories. First, weβll start with the FutureVehicle factory:
public class FutureVehicleCorporation extends Corporation {
@Override
public MotorVehicle createMotorVehicle() {
return new FutureVehicleMotorcycle();
}
@Override
public ElectricVehicle createElectricVehicle() {
return new FutureVehicleElectricCar();
}
}
Now the other one:
public class NextGenCorporation extends Corporation {
@Override
public MotorVehicle createMotorVehicle() {
return new NextGenMotorcycle();
}
@Override
public ElectricVehicle createElectricVehicle() {
return new NextGenElectricCar();
}
}
And itβs done. We complete the implementation using the Abstract Factory Pattern. Hereβs the UML diagram for our custom implementation:
π Abstract Factory Pattern Result4. Factory Method vs. Abstract Factory
To sum up, the Factory Method uses inheritance as a design tool. Meanwhile, Abstract Factory uses delegation. The first relies on a derived class to implement, whereas the base provides expected behavior. Additionally, itβs over-method and not over a class. On the other hand, Abstract Factory is applied over a class. Both follow OCP and SRP, producing a loosely coupled code and more flexibility for future changes in our code base. The creation code is in one place.
5. Conclusion
In this article, we demonstrated the factory design pattern. We described the Factory Method and the Abstract Factory. We provided an example system to illustrate the use of these patterns. Finally, we briefly compared both patterns.
