Factory Method Pattern
An important facet of system design is the manner in which objects are created. One of the most widely used creational patterns is the Factory Method Pattern.
Creational patterns describe object-creation mechanisms that enable greater levels of reuse in evolving systems
Let’s consider that, the client is an object that requires an instance of another object (the product) for some purpose. Rather than creating the product instance directly, the client delegates this responsibility to the factory. Once invoked, the factory creates a new instance of the product, passing it back to the client. Put simply, the client uses the factory to create an instance of the product.
CLIENT ---uses----> FACTORY (Creator) ----create---->PRODUCT
The Factory completely abstracts the creation and initialization of the Product from the Client, which helps client to focus on its discrete role. As the product implementation changes in future, the client remains unchanged.
“Factory Method Pattern defines an interface for creating an object but let’s subclass decide which class to instantiate”
Most implementations of the Factory method pattern use two abstract classes, Factory and Product.
Consider the following example for Factory Method Pattern.
Let consider AbstractProduct.java class as abstract product class which return the cost of the product. This abstract product class is extended and two concrete classes are created i.e. ProductSubClass_One.java and ProductSubClass_Sec.java
ProductSubClass_One.java-This class extends AbstractProduct class and provide first concrete implementation of getProductCost() method.
ProductSubClass_Sec.java-This class extends AbstractProduct class and provide second concrete implementation of getProductCost() method.
Next consider the Factory (Creator) class AbstractCreator.java is an abstract class which contains one method createProduct(String) method for creating the Product.
Now we will create a concrete class of the Factory (creator) i.e. ConcreteCreator.java which override the createProduct (String) method to return object of the concrete Product Sub Class based on the type.
Till now we have created Factory and Product related classes, now we will create a Client class which in turn uses Factory (creator) class to obtain a Product object.
Here in this class we are creating a Factory (creator) object and using this factory object to obtain the product based on “type” which passed as argument in createProduct (String) method.
When we run the Client.java class we will get object of ProductSubClass_One class which gives following output.
Factory method pattern should be used,
- When the object creation depends upon the user data or some event;
- When object which is getting created is abstracted from the user;
- When the type of object created is to be decided at runtime.