Card 01/ 09
Factory Method Pattern: Letting a Subclass Decide Which Object to Create
The base class knows when it needs an object; each subclass knows which one.
The Factory Method pattern defines a method for creating an object in a base class, and lets each subclass override that method to choose the object's class. The code that uses the object is written once, in the base class, and never names a concrete class. This card covers the problem the pattern solves, its intent, and when it is and is not worth using.
The problem is that new EmailSender() ties the line it is on to EmailSender. If an order system notifies customers by email, and the business later wants SMS for some customers, every method that creates a sender has to change. The steps around the creation, building the message and recording that it was sent, are the same for both channels. Only the class differs.
Without the patternthe class is named where the object is used
class OrderNotifier:
def notify_shipped(self, order_id):
sender = EmailSender()
sender.send(f"Order {order_id} has shipped.")Adding SMS means an if here, and in every other method that creates a sender.
With the patternthe class is chosen by a subclass
class OrderNotifier(ABC):
@abstractmethod
def create_sender(self) -> Sender: ...
def notify_shipped(self, order_id):
sender = self.create_sender()
sender.send(f"Order {order_id} has shipped.")SmsOrderNotifier overrides create_sender, and notify_shipped is untouched.
The Gang of Four state the intent as: define an interface for creating an object, but let subclasses decide which class to instantiate. The method that does the creating is the factory method, and the class that declares it is the creator.
Think of a restaurant franchise. Head office writes how every order is served, from greeting to bill, and each branch decides which local dish to cook. The analogy breaks in one place: a branch can change its menu whenever it likes, while each subclass is fixed to the one class its factory method returns.
Factory Method is one of five creational patterns, the family that controls how objects are created.
| Pattern | What it decides |
|---|---|
| Factory Method (this topic) | Which class a subclass creates, through one overridable method. |
| Abstract Factory | Which family of related classes is created, through one object. |
| Builder | How a complex object is put together step by step. |
| Prototype | Which existing object a new one is copied from. |
| Singleton | That a class has only one instance. |
Use it when
- A base class has steps that use an object, and subclasses need different classes of that object.
- A framework must create objects whose classes only the application using it will know.
- A second product class exists, or is planned, and the code around creation is shared.
Avoid it when
- There is only one product class and no sign of a second.
- The class can be passed in as a parameter or a constructor argument instead, which needs no subclass.
- The variation is in a whole family of related objects, which is Abstract Factory's problem.
← → move through sections and cards