Factory method Pattern

Factory method Pattern

Let the subclass decide which class to instantiate. Factory method Pattern


This is a continuation of the software design pattern series. You can checkout the previous posts from my-blog


Factory method pattern

In factory method, the subclass will be the one deciding which class to instantiate.

What do you mean and how it is different from Simple Factory pattern?

In this pattern, no external factory interface(responsible for creating objects) will be passed to the class like in Simple Factory pattern.
Here, it provides an interface for creating products/objects in a super class but allows the subclasses to alter the type of products/objects to be created.


Take the example we saw in Simple Factory pattern in the previous post. Pizzzza <3 Ref: link

Now imagine what if we want to Localize the Pizza store like ChennaiPizzaStore, PunjabPizzaStore, ... How does the code needs to be changed?
Note: It should be changed in such a way that even if N number of such stores come, the code should be extendable.

Interesting. What can be done?

Instead of having an explicit factory interface for creating the product, we can extend the PizzaStore and let the subclasses create their own style of Pizzas.
This is the crux of factory method pattern as the definition says "Define an interface for creating an object, but let subclasses decide which class to instantiate. The Factory method lets a class defer instantiation it uses to subclasses"

Cool. So how to implement Factory method pattern?

In Factory method pattern, four main component gets involved excluding the Client.

  • Product Interface (Pizza)
  • Concrete Product implementations (ChennaiStyleCheesePizza)
  • Abstract Creator class
  • Concrete Creator class

-> ProductInterface

The interface which all the products that can be instantiated should be implementing.

-> Concrete Product implementation

The Concrete classes implementing the Product interface. Example: ChennaiStyleCheesePizza, MumbaiStyleCheesePizze

-> Abstract Creator class

The abstract class which has the abstract method (factory method) for creating the Products which needs to be Overridden by the Child classes and create the respective Product objects.

-> Concrete Creator subclass

The subclass extending the Creator Abstract class overriding the abstract create method (factory method) and having it's own implementation of instantiating the Product classes.


Design Structure

image.png

photo courtesy: link


Sample Code


Ps: Special Thanks to Head First Design Patterns


Thank you. Hope this helps. Looking forward to more learning and sharing. Cheers :)
Connect, share and text me about your views. We can have some discussion :)


Did you find this article valuable?

Support Samuel Johnson R by becoming a sponsor. Any amount is appreciated!