🎨 Design Patterns in Python
Design patterns are typical solutions to common problems in software design. Python's dynamic nature often allows for simpler implementations of these patterns compared to languages like Java or C++.
1️⃣ Singleton Pattern
Ensures a class has only one instance.
Pythonic Way (Module):
Modules are singletons in Python. Just define variables/functions in a module and import it.
Class Way:
class Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
s1 = Singleton()
s2 = Singleton()
print(s1 is s2) # True
2️⃣ Factory Pattern
Creates objects without specifying the exact class of object that will be created.
class Dog:
def speak(self): return "Woof!"
class Cat:
def speak(self): return "Meow!"
def get_pet(pet="dog"):
pets = dict(dog=Dog(), cat=Cat())
return pets[pet]
d = get_pet("dog")
print(d.speak())
3️⃣ Observer Pattern
Defines a dependency between objects so that when one changes state, all its dependents are notified.
class Subject:
def __init__(self):
self._observers = []
def attach(self, observer):
self._observers.append(observer)
def notify(self, message):
for observer in self._observers:
observer.update(message)
class Observer:
def update(self, message):
print(f"Received: {message}")
subject = Subject()
observer = Observer()
subject.attach(observer)
subject.notify("Hello Observers!")
4️⃣ Strategy Pattern
Enables selecting an algorithm at runtime.
import types
class Strategy:
def __init__(self, func=None):
if func:
self.execute = types.MethodType(func, self)
def execute(self):
print("Default Strategy")
def strategy_one(self):
print("Strategy One")
def strategy_two(self):
print("Strategy Two")
s = Strategy(strategy_one)
s.execute() # Strategy One
s = Strategy(strategy_two)
s.execute() # Strategy Two
📝 Summary
- ✅ Singleton: One instance (Modules,
__new__). - ✅ Factory: Object creation abstraction.
- ✅ Observer: Event handling system.
- ✅ Strategy: Swappable algorithms.
- ✅ Pythonic: Python often simplifies these patterns significantly.
Created with ❤️ by Pynfinity