Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

In this tutorial, we’ll explain the factory design pattern in Java. We describe two patterns: Factory Method and Abstract Factory. Both are creational design patterns. We’ll use an example to illustrate these patterns.

2. Factory Method Pattern

First, we need to define an example. We are 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 use the factory method design pattern.

Before we jump into some code, we define a default UML diagram for this pattern:

Factory Method Pattern Default

 

Using the above UML diagram as a reference, we 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.

Let’s jump into code. First, in our example application, we define the MotorVehicle interface. This interface only has a 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 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 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 you can notice, 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 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 Result

3. 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 is not 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 Default

We 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 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 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 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 are ready to build our concrete factories. First, FutureVehicle factory:

public class FutureVehicleCorporation extends Corporation {
    @Override
    public MotorVehicle createMotorVehicle() {
        return new FutureVehicleMotorcycle();
    }
    @Override
    public ElectricVehicle createElectricVehicle() {
        return new FutureVehicleElectricCar();
    }
}

Next, 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 is the UML diagram for our custom implementation:

Abstract Factory Pattern Result

4. 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 is 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 codebase. The creation code is in one place.

5. Conclusion

In conclusion, we did a walkthrough of the factory design pattern. We described the Factory Method and the Abstract Factory. We provide an example system to illustrate the use of these patterns. Additionally, we briefly compared both patterns.

As it is usual, the code snippet is over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.