Factory Method Pattern in Python
Let a factory decide which class to create, so the calling code only works with a common interface.
- Separating creation from use
- A factory method that returns different classes
- Adding a new type without changing callers
Notificationsend(message)EmailNotification"email"SmsNotification"sms"
Ask for an interface, get the right class
The problem
When code creates objects with their concrete class names everywhere (EmailNotification(), SmsNotification()), adding a new channel means finding and editing every place. A factory keeps the choice of class in one spot.
Think of it like this
A factory method is like a vending machine. You press "email" or "sms" and get a ready product; you do not need to know which shelf it came from. Adding a new product means stocking the machine, not changing how customers press buttons.
create_notification("email")🔘 Press the email buttonfactories🗄️ The machine's shelves: name to classfactories[channel]()📦 Build the right productnotification.send("Hello")📨 Use it the same way whatever it isThe Factory Method pattern moves object creation into one function or method that decides which concrete class to build, so callers depend only on the shared interface.
Key points
EmailNotificationandSmsNotificationboth offer the same method,send.factoriesmaps each channel name to its class.factories[channel]()looks up the class and creates an object of it.- The caller only uses
notification.send(...)and never names a concrete class.
When should you use it?
- Choosing a class from configuration or user input, such as a notification channel or file format.
- Hiding complicated construction behind one call.
- Adding new variants without touching the code that uses them.
When not to use it
- Only one class exists and is unlikely to change: calling it directly is clearer.
- Construction needs many optional parts: the Builder pattern fits better.
Example code
class EmailNotification:
# Factory Method: creation is separated from object usage.
def send(self, message):
return f"Email: {message}"
class SmsNotification:
def send(self, message):
return f"SMS: {message}"
def create_notification(channel):
# Centralize the concrete-class selection.
factories = {"email": EmailNotification, "sms": SmsNotification}
return factories[channel]()
notification = create_notification("email")
print(notification.send("Hello"))
Result of running the code
Email: Hello
Code explanation
Both notification classes have a send method, so code that uses them does not care which one it receives. create_notification keeps the mapping from channel names to classes in one dictionary and creates the chosen class with factories[channel](). The caller asks for "email", gets an EmailNotification and simply calls send("Hello").
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Replace the sample domain while preserving the pattern structure.
- Compare the pattern with a simpler implementation and explain the tradeoff.
- Write tests for each participant before adding another implementation.
Common mistakes
Not handling an unknown channel
factories[channel] raises KeyError for an unsupported name.
return factories[channel]()
if channel not in factories:
raise ValueError(f"Unknown channel: {channel}")
return factories[channel]()
Finished this lesson?
Mark it as learned to track your progress.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
- Shape Factory Create shapes from text descriptions with a factory and return the area of each one. Easy