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.

Car.java:

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

Lets create the concrete implementing classes of Car interface .

HondaCar.java:

MarutiCar.java:

TataCar.java:

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

CarFactory.java:

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.

CarFactoryDemo.java:

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

Output:

Related posts

Leave a Comment