Factory Method Pattern — get the gist in 2 min.

aditya chaudhari
JavaDeveloperDiary — JDD
2 min readJul 12, 2022
Factory method pattern

Factory method pattern is all about providing ability to the client class to instantiate an object but without worrying how it’s instantiated, managed and destroyed. The client class has to only request the object and not worry about how it’s been created.

As a formal definition , the factory method pattern defines an interface for creating an object but lets the subclass decide which class to instantiate.

Factory method is also known as a virtual constructor because client only knows a method to create an object ( also knows the return type of an object ) but how and what object is actually created is decided by concrete subclasses.

Structure and the simple example :
PizzaStore is the famous example from Head First design pattern book.
In the example below , we have 2 pizza stores, NYPizzaStore and ChicagoPizzaStore, both has different style of creating standard pizza menu items. Like NYStyleCheesePizza, ChicagoStyleCheesePizza and like that.
But, as the factory method definition says, we have created an interface for creating an object , that interface is the method createPizza() which has return type as Pizza and let subclass decide which class to instantiate means actual pizza object is created by respective concrete pizza objects.
Please refer github code here for more clarity on the above statements.

Have you come across ApplicationContext while working with Spring framework? ApplicationContext use to create IoC Container, ApplicationContext interllay extends the BeanFactory class which is based on Factory Method Pattern where BeanFactory is responsible for creating, managing, caching, wiring beans.

By delegating object creation to the factory method we achieve the single responsibility principle, internally factory method takes care of which product to create.

The real fun is in the details, if you wish to know and understand the pros-cons, java-code example then please consider checking the detailed article at [factory-method-pattern-explained-7-min-read]

Thanks for reading. Love IT, Live IT, Enjoy IT.

On the journey to understand the core essence of design patterns.
Every week I publish a small 2 min post and a long 5–10 min post along with a code example, please consider following if you wish to get notified!

--

--

aditya chaudhari
JavaDeveloperDiary — JDD

building efficient, scalable and maintainable enterprise e-commerce applications using java, spring framework and SAP CC. Life Mantra → Love IT Live IT Enjoy IT