Factory design pattern Complete guide 2019


While taking an interview if you ask any candidates, How many design patterns have you worked on?

Most of the time you will get the exact same answer, singleton , and factory design pattern.

Because factory and singleton both come under the creational design pattern, it helps to resolve the common design problem in the application.

In this article, we will try to understand the Factory design pattern. Along with the use cases of factory design pattern.

Table of Contents

What is the Factory Design Pattern?
Let’s understand the above UML Diagram of the Factory Design Pattern
So, When would you use the Factory Design Pattern?

Difference between factory and abstract factory pattern? Solve the given problem statement by using a factory design pattern

Conclusion

What is the Factory Design Pattern?

Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
In the Factory pattern , we create an object without exposing the creation logic to the client and refer to a newly created object using a common interface.

UML Diagram of Factory Design Pattern In layman term, Name of Factory Design pattern has taken from the real word Factory . The factory takes raw material and produces different-2 products. The same approach we follow in the factory design pattern. We provide some input to the factory class and it will return the object based on the input.

Let’s understand the above UML Diagram of the Factory Design Pattern

As you can see in the above UML diagram. The client application is looking for a logger class where it can log the application data.

Interface : The ILogger interface has one method called log data.

ConcreteImplementations : TextLogger and DatabaseLogger are implementing the ILogger, to log the data in textfiles and database.

IFactory : The IFactory interface has one method called create.

FactoryMethod : The factory class will implement the Ifactory interface to perform the logic and provide the concrete implementation of ILogger based on the input from the user.

Client : The client class will use a factory method to get the instance of ILogger.
So, When would you use the Factory Design Pattern?

The Factory Method pattern is generally used in the following situations:

A different implementation of the common interface should be implemented based on user input.
Every implementation class has its own logic to create the object.
Want to hide the creation logic of object building.
And, while writing the API. If you don’t have the implementation of the interface.

Difference between factory and abstract factory pattern?

...

Top