Factory Method Pattern or Factory Pattern is categorized under creational pattern and this factory pattern just defines an interface or an abstract class for creating an object but subclasses decide which class to instantiate. Hence, subclasses of the factory method are responsible to create instances of the class. The factory method is allowed creating objects without exposing the instantiation logic to the client.
***The factory method pattern is also known as Virtual Constructor.***
The factory method pattern is totally opposite side of Singleton. When you come up with a factory pattern make sure that you have to pass arguments to the constructor, and it must switch the instance that returns depending on the parameters which come in.
When to use factory method pattern?
This pattern can be used in the following situations such as,
- A class doesn’t aware of what subclasses will be required to create.
- A class needs that its subclasses specify the objects to be created.
- The parent class chooses the creation of objects to its subclasses.
Factory Method Usecase:
Assume there is a small-scale restaurant that provides only chicken food items and they have introduced mainly 2 food combinations offers namely ‘Basic Combo Offer’ and ‘Super Combo Offer’ for this Christmas season. These combo offers include several combo items. Customers can able to choose combo offers based on their preferences and they will get combo items according to the combo offer.
Now let’s try to understand the implementation of this scenario according to the factory method.
BigBossBuger, FrenchFries, ChickenFriedRice, ChilliChicken and Soup classes extend from ComboItem abstract class. All those classes are represented the IS-A relationship.
ComboOfferFactory class is also an abstract class it creates ArrayList to store ComboItems and those items are included in different combo offers.
ComboOfferName is an Enum that stores types of combo offers. In this scenario it has two types named “BASIC” and “SUPER”.
‘BasicComboOffer’ and ‘SuperComboOffer’ classes extend from the ‘ComboOfferFactory’ abstract class. when ‘createComboOfer()’ calls it will create related combo items for each combo offer type.
According to the above output, we got combo items related to the ‘BASIC’ combo offer type whereas the second line of the output gave combo items that are included in the ‘SUPER’ combo offer type.
When comparing with singleton pattern, factory pattern is somewhat difficult and complicated to implement as it may have several subclasses to be implemented so there can be lots of coding when going with factory method pattern but this factory method pattern uses abstract class or interface to hide the details of implementation and also it makes the code more robust, loosely coupled and easy to extend.
So here you come to the end of the Factory Method pattern discussion. I’ll meet you guys with another story. 😎