Design Patterns in Python
Design patterns are proven solutions to common programming problems. Learn the most useful Python patterns: Singleton, Factory, Observer, Strategy, and Decorator.
20 min•By Priygop Team•Updated 2026
Design Patterns
Design Patterns
# 1. Singleton — only one instance
class Database:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
cls._instance.connection = "Connected"
return cls._instance
db1 = Database()
db2 = Database()
print(f"Same instance: {db1 is db2}") # True
# 2. Factory — create objects without specifying class
class Dog:
def speak(self): return "Woof!"
class Cat:
def speak(self): return "Meow!"
def animal_factory(animal_type):
animals = {"dog": Dog, "cat": Cat}
return animals.get(animal_type.lower(), Dog)()
pet = animal_factory("cat")
print(pet.speak()) # Meow!
# 3. Observer — notify on changes
class EventEmitter:
def __init__(self):
self._listeners = {}
def on(self, event, callback):
self._listeners.setdefault(event, []).append(callback)
def emit(self, event, data=None):
for callback in self._listeners.get(event, []):
callback(data)
# Usage
emitter = EventEmitter()
emitter.on("login", lambda user: print(f" Welcome, {user}!"))
emitter.on("login", lambda user: print(f" Logging: {user} logged in"))
emitter.emit("login", "Alice")
# 4. Strategy — swap algorithms
class SortStrategy:
@staticmethod
def bubble(data): return sorted(data)
@staticmethod
def reverse(data): return sorted(data, reverse=True)
class Sorter:
def __init__(self, strategy):
self.strategy = strategy
def sort(self, data):
return self.strategy(data)
sorter = Sorter(SortStrategy.reverse)
print(f"\nSorted: {sorter.sort([3, 1, 4, 1, 5])}")Tip
Tip
Use list comprehensions over map/filter. Use generators for large data. Use sets for O(1) lookups. Use dict.get() for safe access.
Diagram
Loading diagram…
Can't instantiate. Must implement all @abstractmethod.
Common Mistake
Warning
Premature optimization. Write clean code first, then profile, then optimize only the bottlenecks.
Quick Quiz
Practice Task
Note
(1) Benchmark list vs set for lookups. (2) Compare comprehension vs loop performance. (3) Optimize a slow function using profiling.