System Design ( Day - 45 )

Manoj KumarManoj Kumar
2 min read

Factory Design Pattern

This design helps to separates the business logic and the object creation part, to decouple every process easily and to improve code readability and maintainability.

Factory
1. Simple Factory
2. Factory Method
3. Abstract Factory Method

1.Simple Factory
A Factory that decides which concrete class to instantiate.
Let’s say we have a class which is Burger this class is a abstract class, in that class we have prepare method that has to be implemented in the concrete classes which are BasicBurger, StandardBurger and PremiumBurger, the prepare method could be written as per the concrete classes needs. new we have to call these classes for that we need objects to pass like if you go to a burger shop then you’ll tell that you need these type of burger right, in a same way we need one factory class to create a objects of burger. that Factory class will create the Objects as per the Client requirements.

2.Factory Method
Defines a Interface for Creating objects but allows sub classes to decide which class to instantiate.
For this method what if we have multiple Factory Classes like in the above example we have only Factory class which is creating the objects, but in this there could be multiple Factory classes could be present, whenever the user is creating the Factory Object he has to pass the Factory object then he has to pass the child objects that has to be implemented for the client. here everything is happening in the runtime, in the run time, it will decide which object to create and which methods to call at the run time.

3.Abstract Factory Method
Provides and Interface for creating families of related objects without specifying their concrete classes.
In the above 2 Methods we only serving Burgers to the customers and with multiple stores but in this Abstract Factory Methods we can serve multiple items from multiple stores, like we can have Burger ( normalBerger, standardBurger, wheatBurger etc…) another item Bread (garlicBread, wheatBread etc…) and also we have Factory abstract class and from that factory abstract class we have 2 stores which is King’sBurger, Singh’sBurger these two stores can serve these items.

Real-World Example
The real world example would be a Notification system which is sending the notification through the sms, push notification for mobile and email notification for these we can have a factory class which is responsible for creating the objects and calling it from the client. like if we wants to send the email then we have to pass the email object.

0
Subscribe to my newsletter

Read articles from Manoj Kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Manoj Kumar
Manoj Kumar