软件设计模式详解
1. 技术分析
1.1 设计模式概述
设计模式是可复用的软件设计方案:
设计模式分类 创建型: 对象创建 结构型: 对象组合 行为型: 对象交互 设计原则: 单一职责 开闭原则 依赖倒置 接口隔离
1.2 创建型模式
创建型模式 Factory Method: 工厂方法 Abstract Factory: 抽象工厂 Builder: 建造者 Prototype: 原型 Singleton: 单例 核心目标: 封装创建逻辑 解耦创建与使用
1.3 结构型模式
结构型模式 Adapter: 适配器 Bridge: 桥接 Composite: 组合 Decorator: 装饰器 Facade: 外观 Flyweight: 享元 Proxy: 代理 核心目标: 优化结构组合 提高复用性
1.4 行为型模式
| 模式 | 用途 | 特点 |
|---|
| Observer | 发布-订阅 | 松耦合 |
| Strategy | 算法切换 | 灵活扩展 |
| Command | 请求封装 | 可撤销 |
| Iterator | 遍历集合 | 统一接口 |
2. 核心功能实现
2.1 工厂模式
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(ABC): @abstractmethod def create_product(self): pass class ConcreteFactoryA(Factory): def create_product(self): return ConcreteProductA() class ConcreteFactoryB(Factory): def create_product(self): return ConcreteProductB() # 使用 factory_a = ConcreteFactoryA() product_a = factory_a.create_product() print(product_a.operation())
2.2 单例模式
class Singleton: _instance = None def __new__(cls): if cls._instance is None: cls._instance = super().__new__(cls) return cls._instance def __init__(self): self.counter = 0 def increment(self): self.counter += 1 return self.counter # 使用 s1 = Singleton() s2 = Singleton() print(s1 is s2) # True print(s1.increment()) # 1 print(s2.increment()) # 2
2.3 观察者模式
class Subject: def __init__(self): self._observers = [] def attach(self, observer): if observer not in self._observers: 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 __init__(self, name): self.name = name def update(self, message): print(f"{self.name} received: {message}") # 使用 subject = Subject() observer1 = Observer("Observer 1") observer2 = Observer("Observer 2") subject.attach(observer1) subject.attach(observer2) subject.notify("Hello World!")
2.4 策略模式
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) # 使用 data = [3, 1, 4, 1, 5, 9] context = Context(ConcreteStrategyA()) print(context.process(data)) # [1, 1, 3, 4, 5, 9] context.set_strategy(ConcreteStrategyB()) print(context.process(data)) # [9, 5, 4, 3, 1, 1]
2.5 装饰器模式
class Component: def operation(self): return "Base operation" class Decorator(Component): def __init__(self, component): self._component = component def operation(self): return self._component.operation() class ConcreteDecoratorA(Decorator): def operation(self): return f"Decorator A({self._component.operation()})" class ConcreteDecoratorB(Decorator): def operation(self): return f"Decorator B({self._component.operation()})" # 使用 component = Component() decorated = ConcreteDecoratorA(ConcreteDecoratorB(component)) print(decorated.operation()) # Decorator A(Decorator B(Base operation))
3. 性能对比
3.1 创建型模式对比
| 模式 | 灵活性 | 复杂度 | 适用场景 |
|---|
| Factory Method | 中 | 低 | 简单对象创建 |
| Abstract Factory | 高 | 中 | 系列产品创建 |
| Builder | 高 | 中 | 复杂对象创建 |
| Singleton | 低 | 低 | 全局唯一实例 |
3.2 结构型模式对比
| 模式 | 解耦程度 | 性能影响 | 适用场景 |
|---|
| Adapter | 高 | 低 | 接口兼容 |
| Decorator | 中 | 低 | 功能增强 |
| Proxy | 高 | 中 | 访问控制 |
3.3 行为型模式对比
| 模式 | 扩展性 | 复杂度 | 适用场景 |
|---|
| Observer | 高 | 中 | 事件通知 |
| Strategy | 高 | 低 | 算法切换 |
| Command | 高 | 中 | 请求封装 |
4. 最佳实践
4.1 模式选择指南
def choose_pattern(problem): patterns = { 'object_creation': 'Factory Method', 'complex_object': 'Builder', 'global_state': 'Singleton', 'interface_adaptation': 'Adapter', 'dynamic_functionality': 'Decorator', 'event_notification': 'Observer', 'algorithm_variation': 'Strategy' } return patterns.get(problem, 'No pattern recommended')
4.2 设计原则应用
# 单一职责 class UserRepository: def save(self, user): pass class UserValidator: def validate(self, user): pass # 开闭原则 class Shape(ABC): @abstractmethod def area(self): pass class Circle(Shape): def area(self): pass
5. 总结
设计模式是软件开发的宝贵财富:
- 创建型:封装对象创建
- 结构型:优化类结构
- 行为型:协调对象交互
- 设计原则:指导模式应用
对比数据如下:
- 工厂模式最常用
- 观察者模式适合事件驱动
- 策略模式提高代码灵活性
- 推荐根据问题选择合适模式