引言:设计模式在Python开发中的重要性
设计模式是软件工程中解决常见问题的可重用解决方案模板。在Python开发中,理解和应用设计模式不仅能提升代码质量,还能帮助开发者避免常见的架构陷阱。Python作为一门动态语言,其设计模式的实现方式与静态语言有所不同,这既带来了灵活性,也引入了独特的挑战。
为什么Python开发者需要学习设计模式?
代码可维护性
:设计模式提供标准化的解决方案,使代码更易于理解和维护
团队协作
:统一的设计模式语言促进团队成员间的有效沟通
架构设计
:帮助构建可扩展、可复用的系统架构
问题解决
:提供经过验证的最佳实践,避免重复造轮子
Python设计模式的特点
Python的动态特性(如鸭子类型、装饰器、元类等)使得某些设计模式的实现更加简洁,但也可能导致滥用。本教程将深入探讨如何在Python中正确应用设计模式,同时避免过度设计。
第一部分:设计模式基础概念
1.1 设计模式的分类
设计模式通常分为三大类:
创建型模式(Creational Patterns)
处理对象创建机制,试图以适合情况的方式创建对象
单例模式(Singleton)
工厂方法模式(Factory Method)
抽象工厂模式(Abstract Factory)
建造者模式(Builder)
原型模式(Prototype)
结构型模式(Structural Patterns)
处理对象组合,形成更大的结构
适配器模式(Adapter)
桥接模式(Bridge)
组合模式(Composite)
装饰器模式(Decorator)
外观模式(Facade)
享元模式(Flyweight)
代理模式(Proxy)
行为型模式(Behavioral Patterns)
处理对象间的职责分配和通信
责任链模式(Chain of Responsibility)
命令模式(Command)
解释器模式(Interpreter)
迭代器模式(Iterator)
中介者模式(Mediator)
备忘录模式(Memento)
观察者模式(Observer)
状态模式(State)
策略模式(Strategy)
模板方法模式(Template Method)
访问者模式(Visitor)
1.2 Python中的设计模式原则
在Python中应用设计模式时,应遵循以下原则:
SOLID原则
:
单一职责原则(Single Responsibility)
开闭原则(Open/Closed)
里氏替换原则(Liskov Substitution)
接口隔离原则(Interface Segregation)
依赖倒置原则(Dependency Inversion)
Python之禅(The Zen of Python)
:
简单优于复杂
明确优于隐式
特殊情况不足以破坏规则
YAGNI原则
:You Aren’t Gonna Need It,避免过度设计
第二部分:创建型模式详解
2.1 单例模式(Singleton)
单例模式确保一个类只有一个实例,并提供全局访问点。
Python实现方式
# 方法1:使用元类
class SingletonMeta(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
instance = super().__call__(*args, **kwargs)
cls._instances[cls] = instance
return cls._instances[cls]
class Database(metaclass=SingletonMeta):
def __init__(self):
self.data = {}
print(“Database initialized”)
def query(self, key):
return self.data.get(key)
def insert(self, key, value):
self.data[key] = value
# 使用示例
db1 = Database()
db2 = Database()
print(db1 is db2) # True
db1.insert(“user”, “Alice”)
print(db2.query(“user”)) # Alice
Pythonic替代方案
# 使用模块级变量(Python推荐方式)
# database.py
class _Database:
def __init__(self):
self.data = {}
def query(self, key):
return self.data.get(key)
def insert(self, key, value):
self.data[key] = value
# 单例实例
instance = _Database()
# 使用时
from database import instance as db
db.insert(“user”, “Bob”)
print(db.query(“user”))
常见陷阱与解决方案
陷阱1:多线程环境下的竞态条件
# 错误实现
class BadSingleton:
def __new__(cls):
if not hasattr(cls, ‘_instance’):
cls._instance = super().__new__(cls)
return cls._instance
# 正确实现(线程安全)
import threading
class ThreadSafeSingleton:
_lock = threading.Lock()
_instance = None
def __new__(cls):
if cls._instance is None:
with cls._lock:
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
陷阱2:继承问题
单例类通常不应该被继承,因为子类可能也需要单例特性,这会导致复杂性。
最佳实践
:
在Python中,优先考虑使用模块级变量而非传统单例
如果必须使用单例,考虑使用依赖注入而非全局状态
避免在单例中存储过多状态,保持其职责单一
2.2 工厂方法模式(Factory Method)
工厂方法模式定义一个创建对象的接口,但让子类决定实例化哪个类。
Python实现
from abc import ABC, abstractmethod
# 抽象产品
class PaymentProcessor(ABC):
@abstractmethod
def process_payment(self, amount):
pass
# 具体产品
class CreditCardPayment(PaymentProcessor):
def process_payment(self, amount):
return f”Processing credit card payment: ${amount}”
class PayPalPayment(PaymentProcessor):
def process_payment(self, amount):
return f”Processing PayPal payment: ${amount}”
class CryptoPayment(PaymentProcessor):
def process_payment(self, amount):
return f”Processing crypto payment: ${amount}”
# 抽象工厂
class PaymentFactory(ABC):
@abstractmethod
def create_processor(self) -> PaymentProcessor:
pass
def process(self, amount):
processor = self.create_processor()
return processor.process_payment(amount)
# 具体工厂
class CreditCardFactory(PaymentFactory):
def create_processor(self) -> PaymentProcessor:
return CreditCardPayment()
class PayPalFactory(PaymentFactory):
def create_processor(self) -> PaymentProcessor:
return PayPalPayment()
class CryptoFactory(PaymentFactory):
def create_processor(self) -> PaymentProcessor:
return CryptoPayment()
# 使用示例
def client_code(factory: PaymentFactory, amount):
print(factory.process(amount))
client_code(CreditCardFactory(), 100)
client_code(PayPalFactory(), 200)
client_code(CryptoFactory(), 300)
Pythonic工厂模式
# 使用字典映射的Pythonic方式
class PaymentSystem:
_processors = {
‘credit_card’: CreditCardPayment,
‘paypal’: PayPalPayment,
‘crypto’: CryptoPayment
}
@classmethod
def get_processor(cls, payment_type):
processor_class = cls._processors.get(payment_type)
if not processor_class:
raise ValueError(f”Unknown payment type: {payment_type}”)
return processor_class()
@classmethod
def process(cls, payment_type, amount):
processor = cls.get_processor(payment_type)
return processor.process_payment(amount)
# 使用
print(PaymentSystem.process(‘credit_card’, 100))
print(PaymentSystem.process(‘paypal’, 200))
实际项目应用
场景:日志系统工厂
import logging
from datetime import datetime
class LoggerFactory:
“””日志系统工厂,支持多种输出目标”””
def __init__(self, config):
self.config = config
def create_logger(self, name):
logger = logging.getLogger(name)
logger.setLevel(self.config.get(‘level’, logging.INFO))
# 清除旧处理器
logger.handlers.clear()
# 根据配置创建处理器
handlers = self._create_handlers()
for handler in handlers:
logger.addHandler(handler)
return logger
def _create_handlers(self):
handlers = []
if self.config.get(‘console’):
handler = logging.StreamHandler()
handler.setFormatter(self._get_formatter())
handlers.append(handler)
if self.config.get(‘file’):
handler = logging.FileHandler(self.config[‘file’])
handler.setFormatter(self._get_formatter())
handlers.append(handler)
if self.config.get(‘http’):
# 假设有HTTPHandler类
handler = HTTPHandler(self.config[‘http_url’])
handler.setFormatter(self._get_formatter())
handlers.append(handler)
return handlers
def _get_formatter(self):
return logging.Formatter(
‘%(asctime)s – %(name)s – %(levelname)s – %(message)s’
)
# 使用示例
config = {
‘console’: True,
‘file’: ‘/var/log/app.log’,
‘level’: logging.DEBUG
}
factory = LoggerFactory(config)
logger = factory.create_logger(‘myapp’)
logger.debug(“This is a debug message”)
logger.info(“Application started”)
2.3 建造者模式(Builder)
建造者模式将一个复杂对象的构建与其表示分离,使得同样的构建过程可以创建不同的表示。
Python实现
class Computer:
def __init__(self):
self.cpu = None
self.ram = None
self.storage = None
self.gpu = None
self.os = None
def __str__(self):
return f”Computer: {self.cpu}, {self.ram} RAM, {self.storage} Storage, {self.gpu}, {self.os}”
class ComputerBuilder:
def __init__(self):
self.computer = Computer()
def set_cpu(self, cpu):
self.computer.cpu = cpu
return self
def set_ram(self, ram):
self.computer.ram = ram
return self
def set_storage(self, storage):
self.computer.storage = storage
return self
def set_gpu(self, gpu):
self.computer.gpu = gpu
return self
def set_os(self, os):
self.computer.os = os
return self
def build(self):
return self.computer
# 使用示例
builder = ComputerBuilder()
computer = (builder
.set_cpu(“Intel i9”)
.set_ram(“32GB”)
.set_storage(“1TB SSD”)
.set_gpu(“RTX 4090”)
.set_os(“Windows 11″)
.build())
print(computer)
Pythonic建造者:使用上下文管理器
from contextlib import contextmanager
class ComputerBuilder:
def __init__(self):
self.computer = Computer()
def __call__(self, **kwargs):
for key, value in kwargs.items():
setattr(self.computer, key, value)
return self
def build(self):
return self.computer
@contextmanager
def build_computer():
builder = ComputerBuilder()
yield builder
return builder.build()
# 使用
with build_computer() as builder:
builder(cpu=”AMD Ryzen 9″, ram=”64GB”, storage=”2TB NVMe”)
# 可以在这里添加更多配置
实际项目应用:API请求构建器
class APIRequestBuilder:
“””用于构建复杂的API请求”””
def __init__(self, base_url):
self.base_url = base_url
self.method = “GET”
self.headers = {}
self.params = {}
self.data = None
self.timeout = 30
def with_method(self, method):
self.method = method.upper()
return self
def with_header(self, key, value):
self.headers[key] = value
return self
def with_auth(self, token):
self.headers[‘Authorization’] = f’Bearer {token}’
return self
def with_param(self, key, value):
self.params[key] = value
return self
def with_json(self, data):
self.data = data
self.headers[‘Content-Type’] = ‘application/json’
return self
def with_timeout(self, seconds):
self.timeout = seconds
return self
def build(self):
“””返回配置好的请求参数”””
return {
‘url’: self.base_url,
‘method’: self.method,
‘headers’: self.headers,
‘params’: self.params,
‘json’: self.data,
‘timeout’: self.timeout
}
# 使用示例
import requests
def client_code():
request_params = (APIRequestBuilder(“https://api.example.com/users”)
.with_method(“POST”)
.with_auth(“secret-token”)
.with_header(“X-Request-ID”, “12345”)
.with_json({“name”: “Alice”, “email”: “alice@example.com”})
.with_timeout(60)
.build())
# 发送请求
response = requests.request(**request_params)
return response
# 在实际项目中,可以进一步封装
class APIClient:
def __init__(self, base_url, auth_token):
self.base_url = base_url
self.auth_token = auth_token
def request(self, method, endpoint, **kwargs):
builder = (APIRequestBuilder(f”{self.base_url}{endpoint}”)
.with_method(method)
.with_auth(self.auth_token))
# 应用其他配置
for key, value in kwargs.items():
if key == ‘json’:
builder.with_json(value)
elif key == ‘params’:
for k, v in value.items():
builder.with_param(k, v)
elif key == ‘headers’:
for k, v in value.items():
builder.with_header(k, v)
elif key == ‘timeout’:
builder.with_timeout(value)
request_params = builder.build()
return requests.request(**request_params)
第三部分:结构型模式详解
3.1 装饰器模式(Decorator)
装饰器模式动态地给对象添加额外的职责,而不改变其结构。
Python中的装饰器模式
Python的装饰器语法糖
@
本质上是装饰器模式的实现。
# 传统装饰器模式实现
class Coffee:
def cost(self):
return 5
def description(self):
return “Basic coffee”
class MilkDecorator:
def __init__(self, coffee):
self._coffee = coffee
def cost(self):
return self._coffee.cost() + 2
def description(self):
return self._coffee.description() + “, milk”
class SugarDecorator:
def __init__(self, coffee):
self._coffee = coffee
def cost(self):
return self._coffee.cost() + 1
def description(self):
return self._coffee.description() + “, sugar”
# 使用
coffee = Coffee()
coffee_with_milk = MilkDecorator(coffee)
coffee_with_milk_and_sugar = SugarDecorator(coffee_with_milk)
print(f”Cost: ${coffee_with_milk_and_sugar.cost()}”) # Cost: $8
print(f”Description: {coffee_with_milk_and_sugar.description()}”)
Python函数装饰器
import time
import logging
from functools import wraps
def timing_decorator(func):
“””计算函数执行时间的装饰器”””
@wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **_kwargs)
end = time.time()
print(f”{func.__name__} executed in {end – start:.4f} seconds”)
return result
return wrapper
def logging_decorator(func):
“””记录函数调用的装饰器”””
@wraps(func)
def wrapper(*args, **kwargs):
logging.info(f”Calling {func.__name__} with args={args}, kwargs={kwargs}”)
try:
result = func(*args, **kwargs)
logging.info(f”{func.__name__} returned {result}”)
return result
except Exception as e:
logging.error(f”{func.__name__} raised {type(e).__name__}: {e}”)
raise
return wrapper
# 组合使用
@timing_decorator
@logging_decorator
def expensive_operation(n):
time.sleep(0.1)
return n * n
# 使用
result = expensive_operation(5)
类装饰器
def singleton(cls):
“””单例模式的类装饰器实现”””
instances = {}
@wraps(cls)
def get_instance(*args, **kwargs):
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return get_instance
@singleton
class DatabaseConnection:
def __init__(self, connection_string):
self.connection_string = connection_string
print(f”Connecting to {connection_string}”)
# 使用
db1 = DatabaseConnection(“postgresql://localhost:5432/mydb”)
db2 = DatabaseConnection(“postgresql://localhost:5432/mydb”)
print(db1 is db2) # True
实际项目应用:缓存装饰器
import hashlib
import json
from functools import lru_cache
class CacheDecorator:
“””通用缓存装饰器,支持TTL”””
def __init__(self, ttl=300, maxsize=128):
self.ttl = ttl
self.maxsize = maxsize
self.cache = {}
self.timestamps = {}
def __call__(self, func):
@wraps(func)
def wrapper(*args, **kwargs):
# 生成缓存键
key = self._make_key(args, kwargs)
# 检查缓存
if key in self.cache:
if time.time() – self.timestamps[key] < self.ttl:
return self.cache[key]
else:
# 过期删除
del self.cache[key]
del self.timestamps[key]
# 计算并缓存
result = func(*args, **kwargs)
# 限制缓存大小
if len(self.cache) >= self.maxsize:
# 删除最旧的
oldest_key = min(self.timestamps, key=self.timestamps.get)
del self.cache[oldest_key]
del self.timestamps[oldest_key]
self.cache[key] = result
self.timestamps[key] = time.time()
return result
return wrapper
def _make_key(self, args, kwargs):
“””生成基于参数的缓存键”””
# 将参数序列化为字符串
data = json.dumps({“args”: args, “kwargs”: kwargs}, sort_keys=True)
return hashlib.md5(data.encode()).hexdigest()
# 使用示例
@CacheDecorator(ttl=60, maxsize=10)
def fetch_user_data(user_id):
“””模拟耗时的数据库查询”””
time.sleep(1) # 模拟延迟
return {“id”: user_id, “name”: f”User {user_id}”, “data”: “some data”}
# 测试
print(“First call:”)
print(fetch_user_data(1))
print(“Second call (cached):”)
print(fetch_user_data(1))
print(“Different parameters:”)
print(fetch_user_data(2))
3.2 适配器模式(Adapter)
适配器模式允许不兼容的接口之间进行合作。
Python实现
# 目标接口
class ModernPaymentSystem:
def process_payment(self, amount, currency):
return f”Processing ${amount} {currency}”
# 不兼容的旧系统
class LegacyPaymentSystem:
def make_payment(self, dollars, cents):
total = dollars + cents / 100
return f”Legacy system: ${total}”
# 适配器
class LegacyPaymentAdapter(ModernPaymentSystem):
def __init__(self, legacy_system):
self.legacy_system = legacy_system
def process_payment(self, amount, currency):
if currency != “USD”:
raise ValueError(“Legacy system only supports USD”)
dollars = int(amount)
cents = int((amount – dollars) * 100)
return self.legacy_system.make_payment(dollars, cents)
# 使用
legacy_system = LegacyPaymentSystem()
adapter = LegacyPaymentAdapter(legacy_system)
print(adapter.process_payment(10.50, “USD”)) # Legacy system: $10.5
# adapter.process_payment(10.50, “EUR”) # Raises ValueError
Pythonic适配器:鸭子类型
# 不需要显式适配器,利用鸭子类型
class ThirdPartyLogger:
def log(self, level, message):
print(f”[{level}] {message}”)
class OurLogger:
def __init__(self, name):
self.name = name
def info(self, message):
print(f”{self.name} INFO: {message}”)
def use_logger(logger):
“””接受任何有log或info方法的logger”””
# 适配逻辑在函数内部
if hasattr(logger, ‘log’):
logger.log(‘INFO’, message)
elif hasattr(logger, ‘info’):
logger.info(message)
else:
raise TypeError(“Logger must have log or info method”)
# 使用
third_party = ThirdPartyLogger()
our_logger = OurLogger(“MyApp”)
use_logger(third_party)
use_logger(our_logger)
实际项目应用:数据库连接适配器
import sqlite3
import psycopg2
from abc import ABC, abstractmethod
class DatabaseAdapter(ABC):
“””统一的数据库接口”””
@abstractmethod
def connect(self, **kwargs):
pass
@abstractmethod
def execute(self, query, params=None):
pass
@abstractmethod
def close(self):
pass
class SQLiteAdapter(DatabaseAdapter):
def __init__(self):
self.conn = None
def connect(self, **kwargs):
self.conn = sqlite3.connect(kwargs[‘database’])
return self
def execute(self, query, params=None):
cursor = self.conn.cursor()
if params:
cursor.execute(query, params)
else:
cursor.execute(query)
return cursor.fetchall()
def close(self):
if self.conn:
self.conn.close()
class PostgreSQLAdapter(DatabaseAdapter):
def __init__(self):
self.conn = None
def connect(self, **kwargs):
self.conn = psycopg2.connect(**kwargs)
return self
def execute(self, query, params=None):
cursor = self.conn.cursor()
if params:
cursor.execute(query, params)
else:
cursor.execute(query)
return cursor.fetchall()
def close(self):
if self.conn:
self.conn.close()
# 工厂函数
def get_database_adapter(db_type, **kwargs):
adapters = {
‘sqlite’: SQLiteAdapter,
‘postgresql’: PostgreSQLAdapter
}
adapter_class = adapters.get(db_type)
if not adapter_class:
raise ValueError(f”Unsupported database type: {db_type}”)
return adapter_class().connect(**kwargs)
# 使用示例
def client_code(adapter: DatabaseAdapter):
# 客户端代码不知道底层数据库类型
result = adapter.execute(“SELECT 1 as test”)
print(result)
# 可以轻松切换数据库
if __name__ == “__main__”:
# SQLite
sqlite_adapter = get_database_adapter(‘sqlite’, database=’:memory:’)
client_code(sqlite_adapter)
sqlite_adapter.close()
# PostgreSQL(如果可用)
try:
pg_adapter = get_database_adapter(
‘postgresql’,
host=’localhost’,
database=’test’,
user=’user’,
password=’password’
)
client_code(pg_adapter)
pg_adapter.close()
except Exception as e:
print(f”PostgreSQL not available: {e}”)
3.3 外观模式(Facade)
外观模式为子系统中的一组接口提供一个统一的接口。
Python实现
# 复杂子系统
class InventorySystem:
def check_stock(self, item_id):
return f”Stock for {item_id}: 10 units”
def update_stock(self, item_id, quantity):
return f”Updated {item_id} stock by {quantity}”
class PaymentSystem:
def process_payment(self, amount, customer_id):
return f”Payment ${amount} processed for customer {customer_id}”
def refund(self, transaction_id):
return f”Refund for transaction {transaction_id} completed”
class ShippingSystem:
def calculate_shipping(self, address, weight):
return f”Shipping cost to {address}: ${weight * 2}”
def schedule_pickup(self, address, date):
return f”Picked up from {address} on {date}”
# 外观
class OrderFacade:
def __init__(self):
self.inventory = InventorySystem()
self.payment = PaymentSystem()
self.shipping = ShippingSystem()
def place_order(self, item_id, quantity, customer_id, address):
“””简化的一站式下单接口”””
# 1. 检查库存
stock_check = self.inventory.check_stock(item_id)
print(stock_check)
# 2. 计算总价(简化)
total_amount = quantity * 50 # 假设单价50
# 3. 处理支付
payment_result = self.payment.process_payment(total_amount, customer_id)
print(payment_result)
# 4. 更新库存
stock_update = self.inventory.update_stock(item_id, -quantity)
print(stock_update)
# 5. 安排配送
shipping_cost = self.shipping.calculate_shipping(address, quantity * 0.5)
print(shipping_cost)
pickup_result = self.shipping.schedule_pickup(address, “2024-01-15″)
print(pickup_result)
return f”Order completed for customer {customer_id}”
# 使用
facade = OrderFacade()
result = facade.place_order(
item_id=”ITEM001″,
quantity=5,
customer_id=”CUST123″,
address=”123 Main St, City”
)
print(“\n” + result)
实际项目应用:微服务协调器
class MicroserviceFacade:
“””协调多个微服务调用的外观模式”””
def __init__(self, service_registry):
self.services = service_registry
def create_user_profile(self, user_data):
“””创建用户资料的复杂流程”””
try:
# 调用用户服务
user_service = self.services.get(‘user’)
user_response = user_service.create(user_data)
# 调用认证服务
auth_service = self.services.get(‘auth’)
auth_response = auth_service.create_credentials(
user_data[’email’],
user_data[‘password’]
)
# 调用通知服务
notification_service = self.services.get(‘notification’)
notification_service.send_welcome_email(
user_data[’email’],
user_data[‘name’]
)
return {
‘status’: ‘success’,
‘user_id’: user_response[‘id’],
‘auth_id’: auth_response[‘id’]
}
except Exception as e:
# 回滚逻辑
self._rollback_user_creation(user_data.get(’email’))
return {‘status’: ‘error’, ‘message’: str(e)}
def _rollback_user_creation(self, email):
“””回滚已创建的用户”””
# 实现回滚逻辑
pass
第四部分:行为型模式详解
4.1 观察者模式(Observer)
观察者模式定义对象间的一对多依赖关系,当一个对象状态改变时,所有依赖者都会收到通知。
Python实现
from abc import ABC, abstractmethod
from typing import List
# 观察者接口
class Observer(ABC):
@abstractmethod
def update(self, subject, event):
pass
# 主题接口
class Subject(ABC):
def __init__(self):
self._observers: List[Observer] = []
def attach(self, observer: Observer):
if observer not in self._observers:
self._observers.append(observer)
def detach(self, observer: Observer):
self._observers.remove(observer)
def notify(self, event):
for observer in self._observers:
observer.update(self, event)
# 具体主题
class Order(Subject):
def __init__(self, order_id):
super().__init__()
self.order_id = order_id
self.status = “pending”
def update_status(self, new_status):
old_status = self.status
self.status = new_status
self.notify({
‘event’: ‘status_change’,
‘order_id’: self.order_id,
‘old_status’: old_status,
‘new_status’: new_status
})
# 具体观察者
class EmailNotifier(Observer):
def update(self, subject, event):
if event[‘event’] == ‘status_change’:
print(f”Email: Order {event[‘order_id’]} changed from {event[‘old_status’]} to {event[‘new_status’]}”)
class SMSNotifier(Observer):
def update(self, subject, event):
if event[‘event’] == ‘status_change’:
print(f”SMS: Order {event[‘order_id’]} is now {event[‘new_status’]}”)
class InventoryUpdater(Observer):
def update(self, subject, event):
if event[‘event’] == ‘status_change’ and event[‘new_status’] == ‘shipped’:
print(f”Inventory: Deducting stock for order {event[‘order_id’]}”)
# 使用
order = Order(“ORD123”)
order.attach(EmailNotifier())
order.attach(SMSNotifier())
order.attach(InventoryUpdater())
order.update_status(“processing”)
print(“—“)
order.update_status(“shipped”)
Pythonic观察者:使用事件系统
from typing import Callable, Dict, List
import asyncio
class EventBus:
“””基于事件总线的观察者模式”””
def __init__(self):
self._handlers: Dict[str, List[Callable]] = {}
def subscribe(self, event_type: str, handler: Callable):
if event_type not in self._handlers:
self._handlers[event_type] = []
self._handlers[event_type].append(handler)
def unsubscribe(self, event_type: str, handler: Callable):
if event_type in self._handlers:
self._handlers[event_type].remove(handler)
def publish(self, event_type: str, data: dict = None):
if event_type in self._handlers:
for handler in self._handlers[event_type]:
handler(data)
# 使用
event_bus = EventBus()
def send_email(data):
print(f”Sending email: {data}”)
def log_event(data):
print(f”Logging: {data}”)
event_bus.subscribe(‘user_registered’, send_email)
event_bus.subscribe(‘user_registered’, log_event)
# 发布事件
event_bus.publish(‘user_registered’, {‘user_id’: 123, ’email’: ‘user@example.com’})
实际项目应用:股票价格监控系统
import random
import time
from threading import Thread, Lock
class StockPriceObserver(Observer):
def __init__(self, name):
self.name = name
def update(self, subject, event):
print(f”{self.name}: Stock {event[‘symbol’]} is now ${event[‘price’]}”)
class StockMarket(Subject):
def __init__(self):
super().__init__()
self.prices = {}
self._lock = Lock()
def set_price(self, symbol, price):
with self._lock:
old_price = self.prices.get(symbol)
self.prices[symbol] = price
if old_price != price:
self.notify({
‘symbol’: symbol,
‘price’: price,
‘change’: price – old_price if old_price else 0
})
def get_price(self, symbol):
with self._lock:
return self.prices.get(symbol)
# 模拟股票价格波动
def price_simulator(market: StockMarket):
symbols = [‘AAPL’, ‘GOOGL’, ‘MSFT’, ‘AMZN’]
while True:
symbol = random.choice(symbols)
price = random.uniform(100, 500)
market.set_price(symbol, round(price, 2))
time.sleep(random.uniform(0.5, 2))
# 使用
market = StockMarket()
market.attach(PriceAlertObserver(“AlertSystem”, threshold=400))
market.attach(StockPriceObserver(“MobileApp”))
market.attach(StockPriceObserver(“WebDashboard”))
# 启动模拟器
simulator_thread = Thread(target=price_simulator, args=(market,), daemon=True)
simulator_thread.start()
# 主线程等待
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
print(“\nStopping…”)
4.2 策略模式(Strategy)
策略模式定义一系列算法,将每个算法封装起来,并使它们可以互换。
Python实现
from abc import ABC, abstractmethod
from typing import List
# 策略接口
class PaymentStrategy(ABC):
@abstractmethod
def pay(self, amount: float) -> str:
pass
# 具体策略
class CreditCardPayment(PaymentStrategy):
def __init__(self, card_number: str, cvv: str):
self.card_number = card_number
self.cvv = cvv
def pay(self, amount: float) -> str:
return f”Paid ${amount} using Credit Card {self.card_number[-4:]}”
class PayPalPayment(PaymentStrategy):
def __init__(self, email: str):
self.email = email
def pay(self, amount: float) -> str:
return f”Paid ${amount} using PayPal account {self.email}”
class CryptoPayment(PaymentStrategy):
def __init__(self, wallet_address: str):
self.wallet_address = wallet_address
def pay(self, amount: float) -> str:
return f”Paid ${amount} using Crypto wallet {self.wallet_address[:8]}…”
# 上下文
class PaymentContext:
def __init__(self, strategy: PaymentStrategy = None):
self._strategy = strategy
def set_strategy(self, strategy: PaymentStrategy):
self._strategy = strategy
def execute_payment(self, amount: float):
if not self._strategy:
raise ValueError(“No payment strategy set”)
return self._strategy.pay(amount)
# 使用
context = PaymentContext()
# 使用信用卡
context.set_strategy(CreditCardPayment(“1234-5678-9012-3456”, “123”))
print(context.execute_payment(100.0))
# 使用PayPal
context.set_strategy(PayPalPayment(“user@example.com”))
print(context.execute_payment(50.0))
# 使用加密货币
context.set_strategy(CryptoPayment(“0x1234567890abcdef”))
print(context.execute_payment(200.0))
Pythonic策略:函数作为一等公民
# 使用函数而非类
def credit_card_payment(card_number: str, cvv: str):
def payment(amount: float):
return f”Paid ${amount} using Credit Card {card_number[-4:]}”
return payment
def paypal_payment(email: str):
def payment(amount: float):
return f”Paid ${amount} using PayPal {email}”
return payment
def crypto_payment(wallet_address: str):
def payment(amount: float):
return f”Paid ${amount} using Crypto {wallet_address[:8]}…”
return payment
# 策略注册表
payment_strategies = {
‘credit_card’: credit_card_payment,
‘paypal’: paypal_payment,
‘crypto’: crypto_payment
}
def process_payment(payment_type: str, amount: float, **kwargs):
strategy_factory = payment_strategies.get(payment_type)
if not strategy_factory:
raise ValueError(f”Unknown payment type: {payment_type}”)
strategy = strategy_factory(**kwargs)
return strategy(amount)
# 使用
print(process_payment(‘credit_card’, 100, card_number=”1234-5678-9012-3456″, cvv=”123″))
print(process_payment(‘paypal’, 50, email=”user@example.com”))
实际项目应用:排序策略
from typing import List, Callable
import time
class Sorter:
“””支持多种排序策略的排序器”””
def __init__(self, data: List[int]):
self.data = data
def sort(self, strategy: Callable[[List[int]], List[int]]) -> List[int]:
start = time.time()
result = strategy(self.data.copy())
end = time.time()
print(f”Sorting took {end – start:.6f} seconds”)
return result
# 策略实现
def bubble_sort(data: List[int]) -> List[int]:
n = len(data)
for i in range(n):
for j in range(0, n – i – 1):
if data[j] > data[j + 1]:
data[j], data[j + 1] = data[j + 1], data[j]
return data
def quick_sort(data: List[int]) -> List[int]:
if len(data) <= 1:
return data
pivot = data[len(data) // 2]
left = [x for x in data if x < pivot]
middle = [x for x in data if x == pivot]
right = [x for x in data if x > pivot]
return quick_sort(left) + middle + quick_sort(right)
def python_sort(data: List[int]) -> List[int]:
return sorted(data)
# 使用
data = [64, 34, 25, 12, 22, 11, 90, 88, 76, 45, 33, 21, 19, 17, 15, 13, 11, 9, 7, 5, 3, 1]
sorter = Sorter(data)
print(“Bubble Sort:”)
print(sorter.sort(bubble_sort))
print(“\nQuick Sort:”)
print(sorter.sort(quick_sort))
print(“\nPython Sort:”)
print(sorter.sort(python_sort))
4.3 命令模式(Command)
命令模式将请求封装为对象,从而使你可用不同的请求对客户进行参数化。
Python实现
from abc import ABC, abstractmethod
from typing import List
# 命令接口
class Command(ABC):
@abstractmethod
def execute(self):
pass
@abstractmethod
def undo(self):
pass
# 具体命令
class CreateDocumentCommand(Command):
def __init__(self, document_name):
self.document_name = document_name
self.created = False
def execute(self):
if not self.created:
print(f”Creating document: {self.document_name}”)
self.created = True
else:
print(f”Document {self.document_name} already exists”)
def undo(self):
if self.created:
print(f”Deleting document: {self.document_name}”)
self.created = False
class WriteTextCommand(Command):
def __init__(self, document, text):
self.document = document
self.text = text
self.previous_text = “”
def execute(self):
self.previous_text = self.document.content
self.document.content += self.text
print(f”Writing to {self.document.name}: {self.text}”)
def undo(self):
self.document.content = self.previous_text
print(f”Undo write to {self.document.name}”)
# 接收者
class Document:
def __init__(self, name):
self.name = name
self.content = “”
# 调用者
class CommandManager:
def __init__(self):
self.history: List[Command] = []
def execute_command(self, command: Command):
command.execute()
self.history.append(command)
def undo_last(self):
if self.history:
command = self.history.pop()
command.undo()
def undo_all(self):
while self.history:
self.undo_last()
# 使用
doc = Document(“MyDoc”)
manager = CommandManager()
# 执行命令
manager.execute_command(CreateDocumentCommand(“MyDoc”))
manager.execute_command(WriteTextCommand(doc, “Hello, “))
manager.execute_command(WriteTextCommand(doc, “World!”))
print(f”Current content: {doc.content}”)
# 撤销
manager.undo_last()
print(f”After undo: {doc.content}”)
manager.undo_last()
print(f”After undo: {doc.content}”)
manager.undo_last()
print(f”After undo: {doc.content}”)
Pythonic命令:使用函数和闭包
from typing import Callable, List
from dataclasses import dataclass
@dataclass
class Command:
execute: Callable
undo: Callable
def create_command(execute_func: Callable, undo_func: Callable) -> Command:
return Command(execute=execute_func, undo=undo_func)
# 命令工厂
class CommandFactory:
@staticmethod
def create_text_command(document, text):
previous_content = document.content
def execute():
document.content += text
print(f”Appended: {text}”)
def undo():
document.content = previous_content
print(f”Undo: {text}”)
return create_command(execute, undo)
@staticmethod
def create_file_command(filename):
created = [False] # 使用列表使其可变
def execute():
if not created[0]:
print(f”Creating file: {filename}”)
created[0] = True
else:
print(f”File {filename} already exists”)
def undo():
if created[0]:
print(f”Deleting file: {filename}”)
created[0] = False
return create_command(execute, undo)
# 使用
class SimpleDocument:
def __init__(self):
self.content = “”
doc = SimpleDocument()
commands: List[Command] = []
# 创建命令
cmd1 = CommandFactory.create_file_command(“test.txt”)
cmd2 = CommandFactory.create_text_command(doc, “Line 1\n”)
cmd3 = CommandFactory.create_text_command(doc, “Line 2\n”)
# 执行
for cmd in [cmd1, cmd2, cmd3]:
cmd.execute()
commands.append(cmd)
print(f”Document content:\n{doc.content}”)
# 撤销
print(“\n— Undoing —“)
while commands:
cmd = commands.pop()
cmd.undo()
实际项目应用:任务队列系统
import time
import threading
from queue import Queue
from abc import ABC, abstractmethod
class TaskCommand(ABC):
@abstractmethod
def execute(self):
pass
@abstractmethod
def get_task_id(self):
pass
class EmailTask(TaskCommand):
def __init__(self, recipient, subject, body):
self.recipient = recipient
self.subject = subject
self.body = body
self.task_id = f”email-{recipient}-{int(time.time())}”
def execute(self):
# 模拟发送邮件
print(f”[{self.task_id}] Sending email to {self.recipient}”)
time.sleep(0.5) # 模拟网络延迟
print(f”[{self.task_id}] Email sent successfully”)
def get_task_id(self):
return self.task_id
class DataProcessingTask(TaskCommand):
def __init__(self, data, operation):
self.data = data
self.operation = operation
self.task_id = f”proc-{int(time.time())}”
def execute(self):
print(f”[{self.task_id}] Processing data: {self.data}”)
time.sleep(1)
result = self.operation(self.data)
print(f”[{self.task_id}] Result: {result}”)
return result
def get_task_id(self):
return self.task_id
class TaskQueue:
def __init__(self):
self.queue = Queue()
self.worker_thread = threading.Thread(target=self._worker, daemon=True)
self.worker_thread.start()
self.completed_tasks = {}
def add_task(self, task: TaskCommand):
self.queue.put(task)
print(f”Task {task.get_task_id()} added to queue”)
def _worker(self):
while True:
task = self.queue.get()
try:
task.execute()
self.completed_tasks[task.get_task_id()] = “SUCCESS”
except Exception as e:
self.completed_tasks[task.get_task_id()] = f”FAILED: {e}”
finally:
self.queue.task_done()
def wait_completion(self):
self.queue.join()
print(“All tasks completed”)
# 使用
queue = TaskQueue()
# 添加任务
queue.add_task(EmailTask(“user@example.com”, “Welcome”, “Welcome to our service”))
queue.add_task(EmailTask(“admin@example.com”, “Alert”, “System check needed”))
queue.add_task(DataProcessingTask([1, 2, 3, 4, 5], sum))
queue.add_task(DataProcessingTask(“hello”, lambda x: x.upper()))
# 等待完成
queue.wait_completion()
print(“\nTask statuses:”)
for task_id, status in queue.completed_tasks.items():
print(f”{task_id}: {status}”)
第五部分:Python高级设计模式与技巧
5.1 元类(Metaclass)模式
元类是类的类,用于控制类的创建。
Python实现
# 元类示例:自动添加方法
class AutoMethodMeta(type):
def __new__(cls, name, bases, attrs):
# 自动添加一个标准方法
if ‘get_class_name’ not in attrs:
attrs[‘get_class_name’] = lambda self: name
# 自动添加属性验证
if ‘__init__’ in attrs:
original_init = attrs[‘__init__’]
def validated_init(self, *args, **kwargs):
# 在初始化前验证
for key, value in kwargs.items():
if key.startswith(‘_’):
raise ValueError(“Private attributes not allowed”)
original_init(self, *args, **kwargs)
attrs[‘__init__’] = validated_init
return super().__new__(cls, name, bases, attrs)
# 使用元类
class User(metaclass=AutoMethodMeta):
def __init__(self, name, email):
self.name = name
self.email = email
# 测试
user = User(name=”Alice”, email=”alice@example.com”)
print(user.get_class_name()) # User
print(user.name) # Alice
# 尝试无效初始化
try:
invalid_user = User(name=”Bob”, _internal=”hack”)
except ValueError as e:
print(f”Error: {e}”)
实际应用:ORM框架
class Field:
def __init__(self, field_type):
self.field_type = field_type
def __set_name__(self, owner, name):
self.name = name
def __get__(self, instance, owner):
if instance is None:
return self
return instance.__dict__.get(self.name)
def __set__(self, instance, value):
if not isinstance(value, self.field_type):
raise TypeError(f”{self.name} must be {self.field_type.__name__}”)
instance.__dict__[self.name] = value
class ModelMeta(type):
“””ORM元类,自动创建字段映射”””
def __new__(cls, name, bases, attrs):
# 收集字段
fields = {}
for key, value in attrs.items():
if isinstance(value, Field):
fields[key] = value
# 存储字段信息
attrs[‘_fields’] = fields
# 创建类
new_class = super().__new__(cls, name, bases, attrs)
# 创建表名(小写类名)
if not hasattr(new_class, ‘_table’):
new_class._table = name.lower()
return new_class
class Model(metaclass=ModelMeta):
def __init__(self, **kwargs):
for key, value in kwargs.items():
if key in self._fields:
setattr(self, key, value)
def save(self):
“””模拟保存到数据库”””
data = {field: getattr(self, field) for field in self._fields}
print(f”Saving {self._table}: {data}”)
# 实际会执行SQL插入
@classmethod
def get(cls, id):
“””模拟从数据库获取”””
print(f”Getting {cls._table} with id={id}”)
# 实际会执行SQL查询
return cls(id=id, name=”Sample”)
# 具体模型
class User(Model):
_table = “users” # 可以自定义表名
id = Field(int)
name = Field(str)
email = Field(str)
class Product(Model):
id = Field(int)
title = Field(str)
price = Field(float)
# 使用
user = User(id=1, name=”Alice”, email=”alice@example.com”)
user.save()
# 类型验证
try:
user.name = 123 # 会失败
except TypeError as e:
print(f”Validation error: {e}”)
product = Product(id=1, title=”Laptop”, price=999.99)
product.save()
5.2 上下文管理器模式
Python的上下文管理器协议(
__enter__
和
__exit__
)是资源管理模式的优雅实现。
Python实现
from contextlib import contextmanager
import time
# 类形式的上下文管理器
class Timer:
def __init__(self, name=”Operation”):
self.name = name
self.start = None
def __enter__(self):
self.start = time.time()
print(f”{self.name} started”)
return self
def __exit__(self, exc_type, exc_val, exc_tb):
end = time.time()
print(f”{self.name} completed in {end – self.start:.4f} seconds”)
if exc_type:
print(f”Exception occurred: {exc_val}”)
# 返回True表示异常已处理,不传播
return False
# 使用
with Timer(“Data processing”):
time.sleep(1)
# 执行一些操作
result = sum(range(1000000))
# 装饰器形式的上下文管理器
@contextmanager
def database_connection(connection_string):
“””数据库连接上下文管理器”””
print(f”Connecting to {connection_string}”)
conn = {“connected”: True, “string”: connection_string}
try:
yield conn # 返回连接对象
finally:
print(“Closing database connection”)
conn[“connected”] = False
# 使用
with database_connection(“postgresql://localhost/db”) as conn:
print(f”Using connection: {conn}”)
# 执行数据库操作
# 嵌套上下文管理器
@contextmanager
def transaction(connection):
print(“Starting transaction”)
try:
yield
print(“Committing transaction”)
except Exception as e:
print(f”Rolling back transaction: {e}”)
raise
# 使用嵌套
with database_connection(“postgresql://localhost/db”) as conn:
with transaction(conn):
print(“Performing database operations”)
# 如果这里抛出异常,会回滚
实际项目应用:文件锁
import fcntl
import os
from contextlib import contextmanager
@contextmanager
def file_lock(filename, timeout=10):
“””文件锁上下文管理器,防止并发访问”””
lock_file = f”{filename}.lock”
fd = None
try:
# 尝试获取锁
start = time.time()
while True:
try:
fd = os.open(lock_file, os.O_CREAT | os.O_EXCL | os.O_RDWR)
break
except FileExistsError:
if time.time() – start > timeout:
raise TimeoutError(f”Could not acquire lock on {filename}”)
time.sleep(0.1)
print(f”Lock acquired for {filename}”)
yield filename
finally:
if fd is not None:
os.close(fd)
os.unlink(lock_file)
print(f”Lock released for {filename}”)
# 使用
def write_to_file(filename, content):
with file_lock(filename):
# 模拟并发写入
with open(filename, ‘a’) as f:
f.write(content + ‘\n’)
time.sleep(0.1) # 模拟耗时操作
# 模拟多线程写入
import threading
threads = []
for i in range(5):
t = threading.Thread(target=write_to_file, args=(“shared.txt”, f”Line {i}”))
threads.append(t)
t.start()
for t in threads:
t.join()
# 查看结果
with open(“shared.txt”) as f:
print(“File contents:”)
print(f.read())
5.3 混入(Mixin)模式
混入是多重继承的一种轻量级替代方案,用于添加可选功能。
Python实现
# 混入类
class TimestampMixin:
“””添加时间戳功能”””
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.created_at = time.time()
self.updated_at = time.time()
def touch(self):
self.updated_at = time.time()
class SerializationMixin:
“””添加序列化功能”””
def to_dict(self):
return {k: v for k, v in self.__dict__.items() if not k.startswith(‘_’)}
@classmethod
def from_dict(cls, data):
return cls(**data)
class ValidationMixin:
“””添加验证功能”””
def validate(self):
for key, value in self.__dict__.items():
if key.startswith(‘_’):
continue
if value is None:
raise ValueError(f”{key} cannot be None”)
return True
# 组合使用
class User(TimestampMixin, SerializationMixin, ValidationMixin):
def __init__(self, name, email):
self.name = name
self.email = email
def __str__(self):
return f”User(name={self.name}, email={self.email})”
# 使用
user = User(“Alice”, “alice@example.com”)
print(user)
print(f”Created at: {user.created_at}”)
# 序列化
data = user.to_dict()
print(f”Serialized: {data}”)
# 验证
try:
user.validate()
print(“Validation passed”)
except ValueError as e:
print(f”Validation failed: {e}”)
# 从字典恢复
restored = User.from_dict(data)
print(f”Restored: {restored}”)
实际项目应用:API视图混入
class JsonResponseMixin:
“””为视图类添加JSON响应能力”””
def json_response(self, data, status=200):
import json
return {
‘status_code’: status,
‘body’: json.dumps(data),
‘headers’: {‘Content-Type’: ‘1.1/json’}
}
class TemplateRenderMixin:
“””为视图类添加模板渲染能力”””
def render_template(self, template_name, context=None):
# 简化的模板渲染
template = f”
{template_name}
”
if context:
for key, value in context.items():
template = template.replace(f”{{{{{key}}}}}”, str(value))
return template
class UserView(JsonResponseMixin, TemplateRenderMixin):
def get_user(self, user_id):
# 模拟数据库查询
return {“id”: user_id, “name”: f”User {user_id}”}
def handle_request(self, request_type, user_id):
if request_type == ‘json’:
user = self.get_user(user_id)
return self.json_response(user)
elif request_type == ‘html’:
user = self.get_user(user_id)
return self.render_template(“user_profile.html”, user)
else:
return self.json_response({“error”: “Invalid request type”}, 400)
# 使用
view = UserView()
print(“JSON Response:”)
print(view.handle_request(‘json’, 123))
print(“\nHTML Response:”)
print(view.handle_request(‘html’, 123))
第六部分:实际项目中的陷阱与最佳实践
6.1 过度设计陷阱
问题识别
# 过度设计的示例:不必要的抽象
class AbstractUserFactory:
@abstractmethod
def create_user(self, data):
pass
class UserFactory(AbstractUserFactory):
def create_user(self, data):
return User(data)
# 实际只需要:
def create_user(data):
return User(data)
解决方案
# 简单函数 vs 复杂模式
# 错误:为简单场景使用复杂模式
class PaymentProcessor:
def __init__(self, strategy):
self.strategy = strategy
def process(self, amount):
return self.strategy.pay(amount)
# 正确:根据复杂度选择
def process_payment(payment_type, amount, **kwargs):
“””简单支付处理函数”””
processors = {
‘credit_card’: lambda amt, **kw: f”CC: ${amt}”,
‘paypal’: lambda amt, **kw: f”PP: ${amt}”,
‘crypto’: lambda amt, **kw: f”BTC: ${amt}”
}
return processors[payment_type](amount, **kwargs)
# 当需要扩展时再重构为策略模式
6.2 单例滥用问题
问题识别
# 错误:全局状态污染
class Config:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
cls._instance.data = {}
return cls._instance
def set(self, key, value):
self.data[key] = value
# 测试时的问题
def test_function():
config = Config()
config.set(“test”, “value”)
# 这会影响其他测试!
# 解决方案:依赖注入
class Config:
def __init__(self, initial_data=None):
self.data = initial_data or {}
def set(self, key, value):
self.data[key] = value
def test_function(config):
config.set(“test”, “value”)
# 不影响全局状态
# 使用
config = Config()
test_function(config) # 明确传递依赖
6.3 装饰器陷阱
问题识别
# 陷阱1:元数据丢失
def my_decorator(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
@my_decorator
def example():
“””This is an example function”””
pass
print(example.__name__) # wrapper
print(example.__doc__) # None
# 解决方案:使用functools.wraps
from functools import wraps
def my_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
@my_decorator
def example():
“””This is an example function”””
pass
print(example.__name__) # example
print(example.__doc__) # This is an example function
陷阱2:装饰器参数处理
# 错误:不支持参数的装饰器
def retry(max_attempts):
def decorator(func):
def wrapper(*args, **kwargs):
for i in range(max_attempts):
try:
return func(*args, **kwargs)
except Exception as e:
if i == max_attempts – 1:
raise
print(f”Attempt {i+1} failed, retrying…”)
return wrapper
return decorator
# 正确:支持参数和不带参数
from functools import wraps
import inspect
def retry(max_attempts=3):
if callable(max_attempts):
# 不带参数调用:@retry
func = max_attempts
max_attempts = 3
@wraps(func)
def wrapper(*args, **kwargs):
for i in range(max_attempts):
try:
return func(*args, **kwargs)
except Exception as e:
if i == max_attempts – 1:
raise
print(f”Attempt {i+1} failed, retrying…”)
return wrapper
else:
# 带参数调用:@retry(5)
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
for i in range(max_attempts):
try:
return func(*args, **kwargs)
except Exception as e:
if i == max_attempts – 1:
raise
print(f”Attempt {i+1} failed, retrying…”)
return wrapper
return decorator
# 使用
@retry
def func1():
pass
@retry(5)
def func2():
pass
6.4 依赖注入最佳实践
问题:硬编码依赖
# 错误
class OrderService:
def __init__(self):
self.db = Database() # 硬编码
self.logger = Logger() # 硬编码
def create_order(self, data):
self.logger.info(“Creating order”)
self.db.save(data)
# 正确:依赖注入
class OrderService:
def __init__(self, db, logger):
self.db = db
self.logger = logger
def create_order(self, data):
self.logger.info(“Creating order”)
self.db.save(data)
# 使用
db = Database()
logger = Logger()
service = OrderService(db, logger)
# 测试时
class MockDB:
def save(self, data):
print(f”Mock save: {data}”)
class MockLogger:
def info(self, msg):
pass
test_service = OrderService(MockDB(), MockLogger())
6.5 性能考虑
问题:模式引入的开销
import time
# 性能测试:装饰器开销
def heavy_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
# 模拟额外工作
for _ in range(1000):
pass
return func(*args, **kwargs)
return wrapper
@heavy_decorator
def fast_function():
return 42
def plain_function():
return 42
# 测试性能差异
start = time.time()
for _ in range(10000):
fast_function()
decorator_time = time.time() – start
start = time.time()
for _ in range(10000):
plain_function()
plain_time = time.time() – start
print(f”Decorator overhead: {((decorator_time/plain_time)-1)*100:.1f}%”)
解决方案:选择性使用
# 只在需要时使用模式
class PerformanceCriticalCode:
def __init__(self, use_pattern=False):
self.use_pattern = use_pattern
def process(self, data):
if self.use_pattern:
# 使用策略模式
return self._process_with_strategy(data)
else:
# 直接实现
return self._process_direct(data)
def _process_with_strategy(self, data):
# 复杂逻辑
return data * 2
def _process_direct(self, data):
# 简单逻辑
return data * 2
第七部分:现代Python特性与设计模式
7.1 数据类(dataclasses)与模式
from dataclasses import dataclass, field
from typing import List, Optional
# 传统模式 vs 数据类
@dataclass
class Order:
“””使用数据类简化不可变对象创建”””
order_id: str
items: List[str] = field(default_factory=list)
total: float = 0.0
status: str = “pending”
def add_item(self, item: str, price: float):
self.items.append(item)
self.total += price
def __post_init__(self):
“””初始化后验证”””
if self.total < 0:
raise ValueError("Total cannot be negative")
# 使用
order = Order(order_id="ORD123")
order.add_item("Laptop", 999.99)
order.add_item("Mouse", 25.50)
print(order)
7.2 协议(Protocols)与结构子类型
from typing import Protocol
# 定义协议
class Drawable(Protocol):
def draw(self) -> str:
…
class Circle:
def draw(self) -> str:
return “Drawing circle”
class Square:
def draw(self) -> str:
return “Drawing square”
# 不需要显式继承
def render_scene(drawables: list[Drawable]):
for item in drawables:
print(item.draw())
# 使用
render_scene([Circle(), Square()])
7.3 异步模式
import asyncio
from typing import List
# 异步观察者模式
class AsyncSubject:
def __init__(self):
self._observers: List[Callable] = []
def attach(self, observer):
self._observers.append(observer)
async def notify(self, event):
tasks = [observer(event) for observer in self._observers]
await asyncio.gather(*tasks)
class AsyncOrder(AsyncSubject):
async def update_status(self, status):
self.status = status
await self.notify({‘status’: status, ‘order_id’: ‘ORD123’})
# 使用
async def email_notifier(event):
await asyncio.sleep(0.1)
print(f”Email: {event}”)
async def sms_notifier(event):
await asyncio.sleep(0.05)
print(f”SMS: {event}”)
async def main():
order = AsyncOrder()
order.attach(email_notifier)
order.attach(sms_notifier)
await order.update_status(“processing”)
asyncio.run(main())
第八部分:总结与最佳实践清单
8.1 何时使用设计模式
✅
应该使用
:
代码重复出现相同模式
需要支持未来扩展
团队协作需要统一语言
复杂对象创建逻辑
需要解耦系统组件
❌
不应该使用
:
简单的一次性脚本
过早优化(YAGNI)
为了使用模式而使用
增加不必要的复杂性
团队不理解的模式
8.2 Python设计模式检查清单
# 设计模式选择指南
def should_use_pattern(problem_description):
checks = {
“is_recurring”: “问题是否重复出现?”,
“is_complex”: “是否涉及复杂对象创建?”,
“needs_extension”: “未来是否需要扩展?”,
“team_understands”: “团队是否理解该模式?”,
“adds_clarity”: “是否提高代码可读性?”
}
score = sum(1 for q in checks.values() if “是” in input(f”{q} (是/否): “))
return score >= 3
# 使用示例
print(“设计模式选择决策工具”)
print(“回答以下问题:”)
if should_use_pattern(“”):
print(“建议使用设计模式”)
else:
print(“保持简单实现”)
8.3 重构指南
# 从简单到模式的演进路径
“””
1. 直接实现 → 识别重复
2. 提取函数 → 识别变化点
3. 封装逻辑 → 引入策略
4. 组合对象 → 引入建造者
5. 事件驱动 → 引入观察者
6. 全局状态 → 引入依赖注入
“””
# 重构检查清单
REFACTORING_CHECKLIST = [
“1. 确保现有测试通过”,
“2. 小步重构,每次验证”,
“3. 保持向后兼容”,
“4. 更新文档和注释”,
“5. 代码审查”,
“6. 性能测试”
]
8.4 推荐资源
书籍
:《Python Cookbook》、《Fluent Python》
工具
:
black
(代码格式化)、
mypy
(类型检查)
库
:
attrs
、
pydantic
、
dependency-injector
实践
:参与开源项目,阅读优秀源码
结论
设计模式是强大的工具,但在Python中需要谨慎使用。记住Python之禅:
简单优于复杂
。优先使用Python内置特性(如函数作为一等公民、装饰器、上下文管理器),只在真正需要时引入经典设计模式。最重要的是,始终以提高代码可读性和可维护性为目标,而不是为了使用模式而使用模式。
通过本教程,你应该能够:
理解核心设计模式的概念和Python实现
识别何时应该使用特定模式
避免常见的陷阱和反模式
在实际项目中应用最佳实践
记住:最好的代码是简单、清晰、易于理解的代码。设计模式是达到这个目标的手段,而不是目的本身。