Importance of Factory method Design Pattern

Factory method example

What is Factory method design pattern

When to use:

  • 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 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.

Real-time examples.
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.lang.Class.newInstance(), java.lang.Class.forName().

Differences between Factory method and Singleton

  • 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

CreditCard example

You can get the factory method pattern code from my GitHub account. It was implemented in java.

Happy Learning.😊