Factory Method Pattern
A subclass decides which concrete object to create, so the code that uses the object never names its class.
Overview
Factory Method is a creational pattern from the Gang of Four book (Gamma, Helm, Johnson and Vlissides, *Design Patterns*, 1994). The idea: a class needs an object but should not decide which concrete class to build. So it declares a method that returns the object, and leaves the choice to subclasses.
The class that declares the method is the Creator. The thing it returns is the Product, described by an interface. Each Concrete Creator overrides the method to return its own Concrete Product. The rest of the Creator's code calls the product through the interface and never learns which class it got.
Interviewers like this pattern because it is a small, clean example of the Open/Closed Principle: a new product means a new subclass, not an edit to existing code. A strong answer draws the two parallel hierarchies, writes the method, and then says honestly when the pattern is more than the problem needs.
The shape of the pattern
The pattern is two parallel hierarchies: creators on one side, products on the other. The diagram shows one pair from the exporter example that follows.
Interview questions
- What is the difference between a simple factory and the Factory Method pattern?
- How does Factory Method support the Open/Closed and Dependency Inversion principles?
- How does Factory Method relate to Template Method and Abstract Factory?
- When is Factory Method more than the problem needs?
- How do you test a class that uses a Factory Method?
Sign up free to read the full topic
More Low-Level Design topics
Start free on Cariara · Coding problems · System design studio