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’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 Default

 

Using 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 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 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 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’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 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’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.

As 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.