What is Factory method design pattern
It is pattern that define an interface or abstract class for creating an object but let the subclasses decide which class to instantiate. In this pattern subclasses are responsible to create the instance. It is also known as Virtual Constructor. It is one of the best way to create an instance where object creation logic is hidden from the client.
When to use:
- When a class doesn’t know what sub-classes will be required to create.
- When a class wants that its sub-classes specify the objects to be created.
- When the parent classes choose the creation of objects to its sub-classes.
- It lets the sub-classes to choose the type of objects to create.
- It promotes the loose-coupling by eliminating the need to bind application-specific classes into the code. That means the code interacts solely with the resultant interface or abstract class, so that it will work with any classes that implement that interface or that extends that abstract class.
This pattern is widely used in JDK, Eg.
1. getInstance() method of java.util.Calendar, NumberFormat, and ResourceBundle.
2. Wrapper classes like Integer, Boolean etc, in Java use this pattern to evaluate the values using valueOf() method.
3. java.nio.charset.Charset.forName(), java.sql.DriverManager#getConnection(), java.net.URL.openConnection(), java.lang.Class.newInstance(), java.lang.Class.forName().
Differences between Factory method and Singleton
- In Singleton no parameter is used, but in Factory method use parameter.
- In Singleton we know the object, In factory method we don’t know the object it will be decided by sub classes.
- In Singleton we will get the same instance, but in factory method, it will be decided by sub classes.
- In Singleton we know the logic, but in factory pattern we don’t know the instantiation logic.
Note : So Singleton and Factory method are working in 2 different ways.
UML diagram for a real time factory pattern example
You can get the factory method pattern code from my GitHub account. It was implemented in java.