DEV Community

qing
qing

Posted on

Python Design Patterns: 5 You Should Know

Python Design Patterns: 5 You Should Know

Design patterns solve common programming problems elegantly.

1. Singleton Pattern

class Database:
    _instance = None

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
            cls._instance.connection = cls._create_connection()
        return cls._instance

    @staticmethod
    def _create_connection():
        return "db_connection"

db1 = Database()
db2 = Database()
assert db1 is db2  # Same instance!
Enter fullscreen mode Exit fullscreen mode

2. Observer Pattern

class EventEmitter:
    def __init__(self):
        self._listeners = {}

    def on(self, event, callback):
        self._listeners.setdefault(event, []).append(callback)

    def emit(self, event, *args):
        for cb in self._listeners.get(event, []):
            cb(*args)

emitter = EventEmitter()
emitter.on('data', lambda x: print(f"Got: {x}"))
emitter.emit('data', 42)
Enter fullscreen mode Exit fullscreen mode

3. Strategy Pattern

from typing import Protocol

class SortStrategy(Protocol):
    def sort(self, data: list) -> list: ...

class BubbleSort:
    def sort(self, data: list) -> list:
        # bubble sort implementation
        return sorted(data)

class QuickSort:
    def sort(self, data: list) -> list:
        return sorted(data, key=lambda x: x)

class Sorter:
    def __init__(self, strategy: SortStrategy):
        self.strategy = strategy

    def sort(self, data):
        return self.strategy.sort(data)

sorter = Sorter(QuickSort())
print(sorter.sort([3, 1, 4, 1, 5]))
Enter fullscreen mode Exit fullscreen mode

4. Factory Pattern

def create_animal(animal_type: str):
    animals = {
        "dog": lambda: Dog(),
        "cat": lambda: Cat(),
        "bird": lambda: Bird(),
    }
    factory = animals.get(animal_type)
    if not factory:
        raise ValueError(f"Unknown animal: {animal_type}")
    return factory()
Enter fullscreen mode Exit fullscreen mode

5. Decorator Pattern

import time
import functools

def timer(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        elapsed = time.time() - start
        print(f"{func.__name__} took {elapsed:.3f}s")
        return result
    return wrapper

@timer
def slow_function():
    time.sleep(0.1)
Enter fullscreen mode Exit fullscreen mode

Follow me for more Python patterns! 🐍

Follow for more Python content!


💡 Related: **Content Creator Ultimate Bundle (Save 33%)* — $30*


If you found this useful, you might like Python Interview Prep Guide — a practical resource that takes things a step further. At $24.99 it's a solid investment for your toolkit.

Top comments (0)