Factory method pattern-Java

Anojaa Gnaneswaran
3 min readMar 15, 2022

--

Factory pattern is one of the most used design patterns in Java. This type of design pattern comes under Creational pattern as this pattern provides one of the best ways to create an object.

In Factory pattern, we create object without exposing the creation logic to the client and refer to newly created object using a common interface.

Factory pattern called as a factory method pattern.

Figure 1: Factory method pattern real world example based on Ice-cream

Usage of Factory Design Pattern

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

Lets see the different between singleton pattern and factory pattern method

  1. Factory pattern we always used parameters to determine which instance we want to get ,Singleton pattern we don’t use parameters when we creating the instance

2. Singleton we always know types of object we going to get,Factory pattern probably we don’t know what types of instance we going to get.

3.Factory pattern we don’t see Initialization logic. Always see what you get. we don’t know how Initialized or Generate happened.

4.Factory pattern Higher class you may reference to Interfaces or some of the concrete classes but as a user you not aware what other parent class should me implemented or inherited.

5.Factory pattern usually uses a higher level of frameworks and then lower levels or the end users or the end developers are the people who are really going to probably invoke it.

Figure 2: Factory method pattern class diagram for Shape

Lets see the sample code for factory method pattern based on decoration.

The final output :

Output of above code

pros of Factory method pattern

  1. Modular expandable of the application
  2. Good testable.
  3. Significant method names

Cons of Factory method pattern

  1. High number of required classes
  2. Too much parallel hierarchy of classes when more number of the product has to be created can be avoided by the prototype.

I hope you now have a better understanding of Factory method pattern

See you in my next article!

Happy coding!

Reference

  1. https://www.javatpoint.com/factory-method-design-pattern
  2. https://www.youtube.com/watch?v=8W-BeJH1aO0&list=PLD-mYtebG3X86i3uyAXwZKfVtUy2gMDdo&index=2

--

--

Anojaa Gnaneswaran

Faculty of IT, University of Moratuwa, Associated Software Engineer at Virtusa