People have been appreciating the effort I am putting in each post these days. Feels good.
Moving on with another design pattern, we have the ‘Factory Design Pattern’. It is also known as the Simple Factory Design Pattern. There exists a very similar pattern named ‘Abstract Factory Design Pattern’. The difference between the design patterns will be discussed once I post about Abstract Factory Design Pattern in my next post.
Lets use the Factory Design Pattern to solve a simple problem.
Lets design a beverage making machine for a cafe. This machine should produce tea, coffee or lemonade. Since, the cafe keeps updating their menu, the solution must be flexible enough to accommodate new beverages in the future.
When should the factory design pattern be used?
- When classes are to be generated at runtime.
- The factory must return one of several objects sharing a common super class.
- Also, when you don’t want the client to know every subclass.
In order to centralize the object creation, lets create an ObjectFactory for beverages, say BeverageFactory.
- BeverageFactory: A singleton factory having a method say [[Beverage makeBeverage(String typeOfBeverage)]]. The method returns an object of Beverage. Thus, makeBeverage returns any sub-class of Beverage. The makeBeverage method holds the object creation strategy.
- Beverage: An abstract class which all the beverages will extend.
Download the implemented code:
Pros and Cons:
- The code for object creation is compact and encapsulated within a single factory.
- Choice of object creation can be made at runtime.
- The system turns loosely coupled, and creation doesn’t depend on the classes of the products to be created.
The only disadvantage with the factory pattern may introduce unnecessary complication into the code. This disadvantage is basically a reference to the YAGNI principle.