Definition
“Factory Method pattern defines an interface/method (a.k.a. factory method) for creating an object, but lets subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses”
Explanation
You declare a factory method in a base creator class (or interface) (e.g.,createDocument() in Application). Concrete
subclasses override it to return specific products (e.g., SpreadsheetDocument, TextDocument). Clients call the factory
method on the base class interface, but the actual subclass controls the product’s type. This decouples product creation
from client code.
Code
In this example, Creator defines the factory methodfactory_method(), and its subclasses (ConcreteCreator1,
ConcreteCreator2) override this method to create specific products (ConcreteProduct1, ConcreteProduct2). The
client code uses a creator without knowing the exact product class.
Analogy
A pizza store example: the base class PizzaStore defines orderPizza(type) which calls the abstract createPizza(type). Subclasses like NYPizzaStore and ChicagoPizzaStore implement createPizza to return region-specific pizzas. The orderPizza steps remain the same, while creation varies by subclass.Interview Insights
Common uses: When a class can’t anticipate the class of objects it must create. Common in frameworks: you extend a base class and provide the object type. Also useful when you want to provide hooks for subclasses to supply products ( e.g. GUI toolkit creating platform-specific widgets).Advantages: Adheres to Open/Closed: new product types can be added by subclassing without modifying base code. Encapsulates object creation code.
Disadvantages: Requires a new subclass for each product variant, leading to many classes. Adds complexity (indirection) for simple cases.\
Alternate Explanation
Problem Statement
When you have a class that needs to create objects, you often use new (in Python, just call the class). But hardcoding which class to instantiate makes the code rigid and harder to extend or change. Imagine you’re ordering food delivery: You don’t care which person prepares your food. You just ask for a “Pizza” or a “Burger”, and the restaurant has a method to decide how and who prepares it.
This “method” is the Factory Method — it decides which concrete class (Chef) will make your product (food).
Notification Example