Python Design Patterns
Common design patterns in Python.
Reusable code solutions.
Singleton Pattern
```python class Database: _instance = None def __new__(cls): if cls._instance is None: cls._instance = super().__new__(cls) return cls._instance
db1 = Database() db2 = Database() print(db1 is db2) # True ```
Factory Pattern
```python class Dog: def speak(self): return "Woof!"
class Cat: def speak(self): return "Meow!"
class AnimalFactory: @staticmethod def create_animal(animal_type): if animal_type == "dog": return Dog() elif animal_type == "cat": return Cat()
animal = AnimalFactory.create_animal("dog") print(animal.speak()) # Woof! ```
Observer Pattern
```python 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 __init__(self, name): self.name = name def update(self, message): print(f"{self.name} received: {message}")
subject = Subject() observer1 = Observer("User1") observer2 = Observer("User2")
subject.attach(observer1) subject.attach(observer2) subject.notify("New update!") ```
Strategy Pattern
```python class PaymentStrategy: def pay(self, amount): pass
class CreditCard(PaymentStrategy): def pay(self, amount): print(f"Paid ${amount} with credit card")
class PayPal(PaymentStrategy): def pay(self, amount): print(f"Paid ${amount} with PayPal")
class ShoppingCart: def __init__(self, payment_strategy): self.payment_strategy = payment_strategy def checkout(self, amount): self.payment_strategy.pay(amount)
cart = ShoppingCart(CreditCard()) cart.checkout(100) ```
Remember
- Patterns solve common problems - Don't overuse - Choose right pattern for problem