factory method pattern diagram

Factory Method Design Pattern – How Factory Works

Factory method design pattern is a creational design pattern that uses factory methods to deal with creating instances without specifying the exact class of the object that will be created. Before you go to example, let us try to understand how factory method pattern works.

How factory method pattern works ?

Let’s look at the factory pattern diagram below

factory method design pattern

In this figure, A is the super class or base class. And classes A1 and A2 are derived classes or sub classes derived from A. The Factory is a class that decides which of these sub classes to be returned depending on the arguments you provide to getA() method.

The getA() method is the factory method that accepts some value type, and returns some instances of the class A and which one it returns does not matter to programmer.

Now let’s see how to do sample program for factory method pattern.

Factory Method Pattern – Super Class

Super class in the factory method pattern can be an interface or abstract class or normal class. For our example we have created abstract super class Vehicle.java with method toString() to print the properties of the object that is created and returned by factory.

Sub Classes – Factory Pattern

Let’s create two sub classes Bike and Car as shown below

Note, both classes should extend Vehicle (Super class)

Factory Class

We are done with super class and sub classes. Now let’s write our Factory class VehicleFactory.java with factory method getVehicle() as shown below

Note: You can keep Factory class as Singleton class or we can write static method like shown above.

Below is our implementation diagram for your understanding

factory method design pattern diagram

Factory method design pattern – Demo

Here is our simple test program to demo factory method pattern

Output

When to use Factory Method Pattern ?

You should consider to use Factory Method Pattern

  • When a class can’t expect what kind of class objects it must create
  • Whenever a class uses its sub classes to specify which objects it creates.

Related Posts

Reference

Leave a Reply

avatar
  Subscribe  
Notify of