Python设计模式:常用模式实战解析
引言
设计模式是解决常见软件设计问题的通用解决方案。作为一名从Python转向Rust的后端开发者,理解设计模式对于编写可维护、可扩展的代码至关重要。本文将深入探讨Python中常用的设计模式,帮助你在实际项目中应用这些模式。
一、创建型模式
1.1 单例模式
class Singleton: _instance = None def __new__(cls, *args, **kwargs): if cls._instance is None: cls._instance = super().__new__(cls, *args, **kwargs) return cls._instance def __init__(self): if not hasattr(self, 'initialized'): self.value = 0 self.initialized = True s1 = Singleton() s2 = Singleton() print(s1 is s2) # True1.2 工厂模式
from abc import ABC, abstractmethod class Product(ABC): @abstractmethod def operation(self): pass class ConcreteProductA(Product): def operation(self): return "Product A operation" class ConcreteProductB(Product): def operation(self): return "Product B operation" class Factory: def create_product(self, type_): if type_ == 'A': return ConcreteProductA() elif type_ == 'B': return ConcreteProductB() else: raise ValueError("Unknown product type") factory = Factory() product = factory.create_product('A') print(product.operation())1.3 建造者模式
class Computer: def __init__(self): self.cpu = None self.ram = None self.storage = None def __str__(self): return f"CPU: {self.cpu}, RAM: {self.ram}, Storage: {self.storage}" 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 build(self): return self.computer builder = ComputerBuilder() computer = builder.set_cpu('Intel i7').set_ram('16GB').set_storage('1TB').build() print(computer)二、结构型模式
2.1 适配器模式
class Target: def request(self): return "Target request" class Adaptee: def specific_request(self): return "Specific request" class Adapter(Target): def __init__(self, adaptee): self.adaptee = adaptee def request(self): return f"Adapter: {self.adaptee.specific_request()}" adaptee = Adaptee() adapter = Adapter(adaptee) print(adapter.request())2.2 装饰器模式
class Component: def operation(self): return "Component operation" class Decorator(Component): def __init__(self, component): self.component = component def operation(self): return f"Decorator: {self.component.operation()}" class ConcreteDecoratorA(Decorator): def operation(self): return f"ConcreteDecoratorA: {self.component.operation()}" component = Component() decorated = ConcreteDecoratorA(component) print(decorated.operation())2.3 代理模式
class Subject: def request(self): pass class RealSubject(Subject): def request(self): return "RealSubject request" class Proxy(Subject): def __init__(self): self.real_subject = None def request(self): if self.real_subject is None: self.real_subject = RealSubject() return f"Proxy: {self.real_subject.request()}" proxy = Proxy() print(proxy.request())三、行为型模式
3.1 观察者模式
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): for observer in self.observers: observer.update(self) class ConcreteSubject(Subject): def __init__(self): super().__init__() self.state = 0 def set_state(self, state): self.state = state self.notify() class Observer: def update(self, subject): pass class ConcreteObserverA(Observer): def update(self, subject): print(f"Observer A: State changed to {subject.state}") class ConcreteObserverB(Observer): def update(self, subject): print(f"Observer B: State changed to {subject.state}") subject = ConcreteSubject() observer_a = ConcreteObserverA() observer_b = ConcreteObserverB() subject.attach(observer_a) subject.attach(observer_b) subject.set_state(10)3.2 策略模式
from abc import ABC, abstractmethod class Strategy(ABC): @abstractmethod def execute(self, data): pass class ConcreteStrategyA(Strategy): def execute(self, data): return sorted(data) class ConcreteStrategyB(Strategy): def execute(self, data): return sorted(data, reverse=True) class Context: def __init__(self, strategy): self.strategy = strategy def set_strategy(self, strategy): self.strategy = strategy def process(self, data): return self.strategy.execute(data) context = Context(ConcreteStrategyA()) print(context.process([3, 1, 4, 1, 5])) context.set_strategy(ConcreteStrategyB()) print(context.process([3, 1, 4, 1, 5]))3.3 模板方法模式
from abc import ABC, abstractmethod class AbstractClass(ABC): def template_method(self): self.base_operation1() self.required_operation1() self.base_operation2() self.hook() def base_operation1(self): print("Base operation 1") def base_operation2(self): print("Base operation 2") @abstractmethod def required_operation1(self): pass def hook(self): pass class ConcreteClass(AbstractClass): def required_operation1(self): print("Concrete operation 1") def hook(self): print("Optional hook") concrete = ConcreteClass() concrete.template_method()四、实战案例:设计模式组合应用
4.1 日志系统设计
class Logger: _instance = None def __new__(cls): if cls._instance is None: cls._instance = super().__new__(cls) cls._instance.handlers = [] return cls._instance def add_handler(self, handler): self.handlers.append(handler) def log(self, message): for handler in self.handlers: handler.handle(message) class Handler: def handle(self, message): pass class ConsoleHandler(Handler): def handle(self, message): print(f"Console: {message}") class FileHandler(Handler): def __init__(self, filename): self.filename = filename def handle(self, message): with open(self.filename, 'a') as f: f.write(f"{message}\n") class FormattingHandler(Handler): def __init__(self, handler, format_): self.handler = handler self.format_ = format_ def handle(self, message): formatted = self.format_.format(message=message) self.handler.handle(formatted) logger = Logger() console = ConsoleHandler() file = FileHandler('app.log') formatted = FormattingHandler(console, "[LOG] {message}") logger.add_handler(formatted) logger.add_handler(file) logger.log("Application started")4.2 数据处理管道
class Pipeline: def __init__(self): self.steps = [] def add_step(self, step): self.steps.append(step) def process(self, data): result = data for step in self.steps: result = step.execute(result) return result class Step: def execute(self, data): pass class ValidateStep(Step): def execute(self, data): if not data: raise ValueError("Empty data") return data class TransformStep(Step): def __init__(self, func): self.func = func def execute(self, data): return self.func(data) class SaveStep(Step): def execute(self, data): print(f"Saving: {data}") return data pipeline = Pipeline() pipeline.add_step(ValidateStep()) pipeline.add_step(TransformStep(lambda x: x.upper())) pipeline.add_step(SaveStep()) pipeline.process("hello world")五、设计模式最佳实践
5.1 选择合适的模式
| 问题类型 | 推荐模式 |
|---|---|
| 对象创建 | 工厂模式、建造者模式 |
| 对象组合 | 适配器模式、装饰器模式 |
| 对象行为 | 观察者模式、策略模式 |
| 对象访问 | 代理模式 |
5.2 避免过度设计
# 不要为简单问题使用复杂模式 # 简单场景:直接创建对象 user = User(name="Alice", age=30) # 复杂场景:使用工厂模式 class UserFactory: @staticmethod def create_admin(name): return User(name=name, role="admin") @staticmethod def create_user(name): return User(name=name, role="user")5.3 遵循SOLID原则
# 单一职责原则 class UserRepository: def save(self, user): pass class UserService: def __init__(self, repository): self.repository = repository def create_user(self, name): user = User(name=name) self.repository.save(user) return user六、设计模式与Rust对比
6.1 Python设计模式
class Singleton: _instance = None def __new__(cls): if cls._instance is None: cls._instance = super().__new__(cls) return cls._instance6.2 Rust设计模式
use std::sync::{Arc, Mutex}; struct Singleton { value: i32, } lazy_static! { static ref INSTANCE: Arc<Mutex<Singleton>> = Arc::new(Mutex::new(Singleton { value: 0 })); } impl Singleton { fn get_instance() -> Arc<Mutex<Self>> { INSTANCE.clone() } }6.3 对比分析
| 特性 | Python | Rust |
|---|---|---|
| 实现复杂度 | 较低 | 较高 |
| 线程安全 | 需要手动处理 | 编译时保证 |
| 性能 | 有运行时开销 | 零成本抽象 |
| 灵活性 | 较高 | 较低 |
总结
设计模式是编写高质量代码的重要工具。通过本文的学习,你应该掌握了以下核心要点:
- 创建型模式:单例模式、工厂模式、建造者模式
- 结构型模式:适配器模式、装饰器模式、代理模式
- 行为型模式:观察者模式、策略模式、模板方法模式
- 实战案例:日志系统、数据处理管道
- 最佳实践:选择合适模式、避免过度设计、遵循SOLID原则
- 与Rust对比:实现方式和特性差异
作为从Python转向Rust的后端开发者,理解设计模式有助于你在两种语言之间进行有效的思维转换。虽然Rust的类型系统和所有权模型改变了某些模式的实现方式,但核心思想是相通的。