Other Tutorials

Factory Method Design Pattern

Introduction:

Factory Method pattern is one of the popular creational design patterns. It doesn’t specifically rely on a factory object to create the objects. Rather, the idea is to use a separate method in the same class to create an object.

Factory Method pattern defines an interface for creating objects but lets the subclasses decide how to instantiate its objects. Each subclass must define its Factory Method.

In this tutorial, we’ll learn how to implement a Factory Method design pattern with the help of an example of a VehicleStore.

Defining a VehicleStore:

Let’s start by defining a VehicleStore class:

Where the VehicleType is an enum defining the type of vehicle:

Note that we have defined the createVehicle() method as abstract; the one which will be responsible for the creation of a specific type of a vehicle.

Defining SubClasses:

Now, let’s say we have two types of a VehicleStoreLightVehiclesStore and HeavyVehiclesStore:

The LightVehiclesStore is responsible for selling lightweight vehicles like a bike or a car. On the other hand, HeavyVehiclesStore sells trucks and cranes.

As we can see, both of these subclasses override the createVehicle() method.

UML Diagram for Our Example:

We can represent the above example with a UML diagram similar to:

Factory Method Pattern Example

The type of Vehicle we create is decided in the concrete subclasses. Also, we have exposed the VehicleStore as the common interface for these subclasses.

We can further go a step ahead and define a Factory Object for the VehicleStore to avoid exposing these subclasses directly to the client code.

Conclusion:

In this tutorial, we explored an important creational pattern – the Factory Method Pattern. The central idea of this pattern is to let the subclasses decide how to instantiate objects.

Some of the popular implementations of this pattern are available in our Java API. Some of these include Calendar.getInstance(), java.text.NumberFormat.getInstance() and java.util.ResourceBundle.getBundle() methods.

Be the First to comment.

Leave a Comment

Your email address will not be published. Required fields are marked *