Jonas Kemper

Design Patterns with Python Examples - Part 1 - The Factory Method Pattern

Overview: The Factory Method pattern provides a way to delegate the instantiation logic to subclasses. Instead of calling a constructor directly, we call a method that returns the appropriate type of object.

Example Use Case: A notification system that can send messages via email or SMS.

from abc import ABC, abstractmethod

class Notification(ABC):
    @abstractmethod
    def notify(self, message: str):
        pass

class EmailNotification(Notification):
    def notify(self, message: str):
        print(f"Sending EMAIL with message: {message}")

class SMSNotification(Notification):
    def notify(self, message: str):
        print(f"Sending SMS with message: {message}")

class NotificationFactory:
    def create_notification(self, channel: str) -> Notification:
        if channel == 'email':
            return EmailNotification()
        elif channel == 'sms':
            return SMSNotification()
        else:
            raise ValueError("Unknown notification channel")

factory = NotificationFactory()
notif = factory.create_notification('sms')
notif.notify("Factory pattern works!")

Why it’s useful: It separates object creation from business logic and allows flexibility in adding new notification types later.