Factory Design Pattern


What is Factory Design Pattern ?

Factory Design Pattern is a creational design pattern. This pattern says that define an interface or abstract class for creating an object but let the sub-classes decide which class to instantiate which means that sub-classes are responsible for creating an instance of the class.

When to use Factory Design Pattern ?

  • When a class cannot anticipate the type of objects it needs to create beforehand.
  • When a class requires its sub-classes to specify the type of objects that it creates.
  • Most suitable where there is some complex object creation logic is involved.


Let’s implement this design pattern.

To implement this design pattern lets take an example of Car factory which manufactures Car. Car is a real entity and hence Car factory is creating different types of Car objects. Lets create all the classes required to implement this design pattern.


Create Car interface which will just return the name of  Car.

Lets create the concrete implementing classes of Car interface .




Now create the CarFactory.java class which will create the Car objects.


Till now, we have created a Car interface, concrete classes implementing the Car interface and CarFactory class. Lets create the CarFactory demo class which will explain how the Car objects are created.


We have created all the required classes. Lets run our Demo class to check the output:


Related posts

Leave a Comment