You can usually tell when a codebase needs design patterns because everyone starts inventing their own. You'll see three different "event systems," two "config loaders," and one brave soul who passed a database connection through 19 function calls like a cursed relay baton.
Design patterns aren't magical. They're just names for shapes that show up over and over. If you've got enough curiosity (and enough bugs), you start to recognize the shapes. Then system design gets simpler: you recognize the shape, you know what it does, and you know whether it fits your problem.
Below are three patterns I actually see in Python code that ships: Singleton, Factory, and Observer. They can make your code cleaner. They can also make it worse. Both outcomes are very achievable.
Design patterns are templates, not collectibles
A pattern is not an off-the-shelf component. It's a reusable plan.
The trap is treating patterns like Pokémon. "Gotta catch 'em all." That's how you end up with a tiny script that has AbstractBaseFactories and a ServiceLocator and a sad little TODO file begging for mercy.
Use patterns when they remove friction:
- fewer "special cases"
- clearer ownership of state
- fewer spaghetti dependencies
- easier testing (yes, sometimes)
Singleton: one instance, one source of truth
Singleton is the "there should only be one of these" pattern. Common targets:
- config managers
- shared caches
- connection pools (careful here)
- a central "data manager" object
A typical Python way is overriding __new__:
class Config:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
cls._instance.values = {}
return cls._instance
c1 = Config()
c2 = Config()
assert c1 is c2
Warning: Singleton is global state with a nicer outfit. Overuse it and your tests get weird fast. You'll also couple code that shouldn't know about each other.
I once debugged a system where someone had created five different Singleton implementations. Each one thought it was the only one. The irony was not lost on me, but the three hours weren't funny.
If you can pass an object as a parameter (or, gasp, use dependency injection), do that first. Singleton is for the cases where passing it around turns your function signatures into a phone book.
Factory: centralize object creation without hard-coding classes everywhere
Factories help when you need to create different concrete types behind a shared interface. Example: a game enemy system.
from abc import ABC, abstractmethod
class Enemy(ABC):
@abstractmethod
def attack(self) -> str: ...
class Orc(Enemy):
def attack(self) -> str:
return "Orc swings a club"
class Dragon(Enemy):
def attack(self) -> str:
return "Dragon breathes fire"
class EnemyFactory:
@staticmethod
def create_enemy(enemy_type: str) -> Enemy:
if enemy_type == "orc":
return Orc()
if enemy_type == "dragon":
return Dragon()
raise ValueError(f"Unknown enemy_type={enemy_type}")
This is useful when the type is decided at runtime (config, user input, feature flags). It also keeps creation logic in one place.
Warning: Don't add a factory just because you can. If you have two classes and they never change, a factory is just extra indirection. This is a classic case of best practices becoming antipatterns when applied without thought.
Observer: subscriptions and notifications without tight coupling
Observer is the "tell everyone who cares" pattern. GUI frameworks use it. Event systems use it. Anything reactive uses it.
class Subject:
def __init__(self):
self._observers = []
self._state = None
def attach(self, obs):
self._observers.append(obs)
def detach(self, obs):
self._observers.remove(obs)
def notify(self):
for obs in list(self._observers):
obs.update(self._state)
def set_state(self, state):
self._state = state
self.notify()
class Observer:
def update(self, state): ...
class PrintObserver(Observer):
def update(self, state):
print(f"state changed: {state}")
Warning: Observer can become a performance problem if you notify constantly or you have lots of observers. Also watch lifetimes. If you keep references to observers forever, you've invented a memory leak with extra steps.
A real combined example: weather monitoring
Here's a small system that uses all three patterns together:
- Singleton: one WeatherDataManager
- Factory: create stations based on type
- Observer: displays subscribe to updates
from abc import ABC, abstractmethod
class WeatherStation(ABC):
@abstractmethod
def collect_data(self) -> dict: ...
class BasicWeatherStation(WeatherStation):
def collect_data(self) -> dict:
return {"temp": 20, "humidity": 50, "pressure": 1013}
class AdvancedWeatherStation(WeatherStation):
def collect_data(self) -> dict:
return {"temp": 20.5, "humidity": 49.8, "pressure": 1012.8}
class WeatherStationFactory:
@staticmethod
def create(station_type: str) -> WeatherStation:
if station_type == "basic":
return BasicWeatherStation()
if station_type == "advanced":
return AdvancedWeatherStation()
raise ValueError(station_type)
class WeatherDisplay(ABC):
@abstractmethod
def update(self, data: dict): ...
class TemperatureDisplay(WeatherDisplay):
def update(self, data: dict):
print(f"Temp: {data['temp']}")
class HumidityDisplay(WeatherDisplay):
def update(self, data: dict):
print(f"Humidity: {data['humidity']}")
class WeatherDataManager:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
cls._instance._observers = []
cls._instance._data = {}
return cls._instance
def attach(self, display: WeatherDisplay):
self._observers.append(display)
def notify(self):
for obs in list(self._observers):
obs.update(self._data)
def ingest(self, data: dict):
self._data = data
self.notify()
## wiring
manager = WeatherDataManager()
manager.attach(TemperatureDisplay())
manager.attach(HumidityDisplay())
station = WeatherStationFactory.create("advanced")
manager.ingest(station.collect_data())
That's the whole machine: one manager, swappable input sources, and decoupled outputs.
Use patterns when they make the code simpler. Skip them when they don't. That's the whole game.
-Sethers