====== 第十七章:设计模式 ======
===== 本章目标 =====
完成本章学习后,你将能够:
* 理解常用设计模式
* 在Python中实现经典设计模式
* 选择合适的设计模式解决问题
===== 创建型模式 =====
==== 单例模式 ====
# 方式1:使用__new__
class Singleton:
_instance = None
def __new__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
# 方式2:使用装饰器
def singleton(cls):
instances = {}
def wrapper(*args, **kwargs):
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return wrapper
@singleton
class Logger:
def __init__(self):
self.logs = []
==== 工厂模式 ====
class Animal:
def speak(self):
pass
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
class AnimalFactory:
@staticmethod
def create(animal_type):
if animal_type == "dog":
return Dog()
elif animal_type == "cat":
return Cat()
raise ValueError(f"Unknown animal type: {animal_type}")
# 使用
animal = AnimalFactory.create("dog")
print(animal.speak()) # Woof!
===== 结构型模式 =====
==== 装饰器模式 ====
class Coffee:
def cost(self):
return 5
def description(self):
return "Coffee"
class Decorator(Coffee):
def __init__(self, coffee):
self._coffee = coffee
def cost(self):
return self._coffee.cost()
def description(self):
return self._coffee.description()
class Milk(Decorator):
def cost(self):
return self._coffee.cost() + 1
def description(self):
return self._coffee.description() + ", Milk"
class Sugar(Decorator):
def cost(self):
return self._coffee.cost() + 0.5
def description(self):
return self._coffee.description() + ", Sugar"
# 使用
coffee = Coffee()
coffee = Milk(coffee)
coffee = Sugar(coffee)
print(coffee.description()) # Coffee, Milk, Sugar
print(coffee.cost()) # 6.5
===== 行为型模式 =====
==== 观察者模式 ====
class Subject:
def __init__(self):
self._observers = []
def attach(self, observer):
self._observers.append(observer)
def detach(self, observer):
self._observers.remove(observer)
def notify(self, message):
for observer in self._observers:
observer.update(message)
class Observer:
def update(self, message):
pass
class EmailObserver(Observer):
def update(self, message):
print(f"Email notification: {message}")
class SMSObserver(Observer):
def update(self, message):
print(f"SMS notification: {message}")
# 使用
subject = Subject()
subject.attach(EmailObserver())
subject.attach(SMSObserver())
subject.notify("New order received!")
==== 策略模式 ====
from abc import ABC, abstractmethod
class PaymentStrategy(ABC):
@abstractmethod
def pay(self, amount):
pass
class CreditCardPayment(PaymentStrategy):
def pay(self, amount):
print(f"Paying ${amount} using Credit Card")
class PayPalPayment(PaymentStrategy):
def pay(self, amount):
print(f"Paying ${amount} using PayPal")
class ShoppingCart:
def __init__(self):
self.items = []
self._strategy = None
def set_payment_strategy(self, strategy):
self._strategy = strategy
def checkout(self, amount):
if self._strategy:
self._strategy.pay(amount)
else:
raise ValueError("Payment strategy not set")
# 使用
cart = ShoppingCart()
cart.set_payment_strategy(CreditCardPayment())
cart.checkout(100)
cart.set_payment_strategy(PayPalPayment())
cart.checkout(50)
===== 本章练习 =====
1. 实现建造者模式构建复杂对象
2. 实现适配器模式统一接口
3. 实现命令模式支持撤销操作
4. 实现模板方法模式
下一章:[[python_course:chapter18|第十八章:文件操作]]