Design Patterns in Python: Singleton, Factory, Observer
As software projects scale from simple scripts into enterprise applications, managing object creation, state synchronization, and component coupling becomes critical. Design patterns are tried-and-tested architectural blueprints and best practices developed by experienced engineers to solve recurring object-oriented design problems.
While Python’s dynamic nature allows for flexible coding styles, applying foundational design patterns ensures your code remains maintainable, modular, and extensible. This comprehensive guide covers three essential design patterns every Python developer should master: Singleton (Creational), Factory (Creational), and Observer (Behavioral).
1. Singleton Pattern: Ensuring a Single Class Instance
The Singleton pattern restricts the instantiation of a class to one single object and provides a global point of access to that instance. This is particularly useful in Python for database connection pools, logger configurations, or application setting managers.
# Python Singleton Implementation using __new__
class DatabaseConnection:
_instance = None
def __new__(cls, *args, **kwargs):
if cls._instance is None:
print("Initializing database connection instance...")
cls._instance = super(DatabaseConnection, cls).__new__(cls)
return cls._instance
def __init__(self):
if not hasattr(self, 'initialized'):
self.connection_url = "postgresql://admin:secret@localhost:5432/app_db"
self.initialized = True
# Usage
db1 = DatabaseConnection()
db2 = DatabaseConnection()
print(db1 is db2) # Output: True (Both variables point to the exact same memory instance)
2. Factory Method Pattern: Encapsulating Object Creation
The Factory pattern provides an interface for creating objects in a superclass, but allows subclasses or factory functions to alter the type of objects that will be created. This decouples object instantiation logic from client code.
from abc import ABC, abstractmethod
# Abstract Product
class Notification(ABC):
@abstractmethod
def send(self, message: str) -> None:
pass
# Concrete Products
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}")
# Factory Class
class NotificationFactory:
@staticmethod
def create_notification(notification_type: str) -> Notification:
if notification_type == "email":
return EmailNotification()
elif notification_type == "sms":
return SMSNotification()
raise ValueError(f"Unknown notification type: {notification_type}")
# Usage
factory = NotificationFactory()
notifier = factory.create_notification("email")
notifier.send("Welcome to CodeCrown!")
3. Observer Pattern: Establishing Event-Driven Subscriptions
The Observer pattern defines a subscription mechanism to notify multiple objects (observers) about any events that happen to the object they are observing (the subject). This is widely used in event-driven systems, UI frameworks, and logging hooks.
# Subject and Observer Implementation
class Subject:
def __init__(self):
self._observers = []
def attach(self, observer):
self._observers.append(observer)
def detach(self, observer):
self._observers.remove(observer)
def notify(self, message):
for observer in self._observers:
observer.update(message)
class LoggerObserver:
def update(self, message):
print(f"[Logger]: Event received -> {message}")
class AnalyticsObserver:
def update(self, message):
print(f"[Analytics]: Tracking event -> {message}")
# Usage
subject = Subject()
subject.attach(LoggerObserver())
subject.attach(AnalyticsObserver())
subject.notify("User signed up successfully!")
Conclusion
Mastering software design patterns in Python—such as enforcing single instances with the Singleton pattern, centralizing instantiation logic with the Factory pattern, and decoupling event handling with the Observer pattern—empowers developers to write cleaner, more resilient, and easily scalable object-oriented code.