Factory Pattern — Explained with Examples
The Factory pattern provides an interface for creating objects without specifying their concrete classes, encapsulating object creation logic.
Factory is a creational design pattern that delegates object instantiation to a dedicated method or class. Instead of calling new directly, you call a factory method that decides which concrete class to instantiate based on context.
Why Factory Matters
Direct instantiation with new couples your code to specific classes. When creation logic is complex (conditional, requires setup, depends on configuration), scattering it throughout the codebase violates DRY and makes changes painful. A factory centralizes creation, making it easy to extend or swap implementations.
Real-World Analogy
A car factory. You order a “sedan” without knowing whether it will be built from parts sourced from Supplier A or Supplier B. The factory decides which parts to use and assembles the car. You get back a working vehicle without being coupled to the supplier details.
Example: Factory Pattern
from abc import ABC, abstractmethod
class Notification(ABC):
@abstractmethod
def send(self, message: str): pass
class EmailNotification(Notification):
def send(self, message: str):
print(f"Sending email: {message}")
class SMSNotification(Notification):
def send(self, message: str):
print(f"Sending SMS: {message}")
class PushNotification(Notification):
def send(self, message: str):
print(f"Sending push: {message}")
# Factory encapsulates creation logic
class NotificationFactory:
@staticmethod
def create(channel: str) -> Notification:
if channel == "email":
return EmailNotification()
elif channel == "sms":
return SMSNotification()
elif channel == "push":
return PushNotification()
else:
raise ValueError(f"Unknown channel: {channel}")
# Client code doesn't know about concrete classes
factory = NotificationFactory()
notifier = factory.create("email")
notifier.send("Welcome to our service!")Expected output: Sending email: Welcome to our service!
Related Terms
Singleton, Dependency Injection, Dependency Inversion Principle, Factory
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro