Tuesday, March 22, 2022

SKP's GoF Design Patterns a Day - 03 - Factory Method

[GitHub Repository for Code Samples]

Was going through the book ‘Head First Design Patterns’, came up with my own examples to understand them further. Try downloading the code and see if it helps you in comprehending these in a better way.


Factory Pattern
Factory Pattern, I am made to believe, is the most widely used and implemented pattern in software projects after the Singleton Pattern. Since Singleton is only a creational pattern at single class level, the scale of the effect of usage of Factory should be much higher. Factory Pattern deals with creation of similar type of objects and production in a centralized manner, depending on the condition or type of object requested. There are variations of the usage of factory pattern, three of which I have enlisted below:

1. Simple Factory [Sample Code]
The simplest factory is the one that is used to create (instantiate) a specific type of product (object) depending on a condition. The specific types of objects that can be created in a single factory are all expected to implement a single interface.

In the attached example, the factory is used to instantiate a specific type of object depending on the operating system. All the specific systems implement the System interface, which defines the common methods that the concrete class of this type should implement. SystemFactory is the factory class which provides the create() method which takes a type argument. The type argument decides which concrete factory should be instantiated.

2. Factory Method [Sample Code]
When there can be various families of products (objects) that which can be instantiated, but each family of these product needs to be created by a specific type of factory, we define a factory method in the base factory class. The concrete implementations of the base factory then override this method to produce concrete type of products, depending on the condition.
Fig. 5 : Factory Method (Creational) Design Pattern - Class Diagram 
[Source : Wikipedia]

In the example, you can notice the presence of two abstract classes, Mobile (Product) and MobileStore (Creator). One family of concrete product implementations are NokiaASeries, NokiaBSeries and NokiaCSeries to be created by the NokiaStore, which is the concrete implementation of the creator. In similar fashion another family of products such as SonyASeries, SonyBSeries and SonyCSeries are to be created by SonyStore, another concrete implementation of MobileStore. MobileStoreCentre is the main class to run this application. The createMobile() method is the abstract method (factory method) that is to be overridden by the creator implementations.

No comments: