结合AI进行汇总,方便随时查找,若有错误可以指出。
模式关系图谱
扩展 增强 替换 通知 控制 封装 创建型 单例 工厂方法 抽象工厂 建造者 原型 结构型 适配器 桥接 组合 装饰器 外观 享元 代理 行为型 职责链 命令 解释器 迭代器 中介者 备忘录 观察者 状态 策略 模板方法 访问者
异同点汇总
一、创建型模式(5种)
模式 | 核心目的 | 关键特点 | 典型应用场景 |
---|---|---|---|
单例(Singleton) | 确保类只有一个全局实例 | 严格控制实例化过程,提供全局访问点 | 配置管理、线程池、日志系统 |
工厂方法(Factory Method) | 由子类决定创建的具体对象 | 解耦客户端和具体类,支持扩展 | 跨平台UI组件、数据库连接器 |
抽象工厂(Abstract Factory) | 创建相关对象家族 | 强调产品组合,易于切换整个产品族 | 跨风格UI套件、主题系统 |
建造者/生成器(Builder) | 分步构造复杂对象 | 分离构造过程与表示,支持不同配置 | 复杂文档生成、餐品定制 |
原型(Prototype) | 通过复制现有对象创建新对象 | 避免重复初始化,动态添加对象 | 游戏实体克隆、配置模板 |
二、结构型模式(7种)
模式 | 核心目的 | 关键特点 | 典型应用场景 |
---|---|---|---|
适配器(Adapter) | 转换接口使不兼容类协作 | 包装旧接口,复用已有类 | 集成遗留系统、API兼容层 |
组合(Composite) | 统一处理树形结构的单个对象和组合对象 | 递归结构,客户端一致操作 | 文件系统、UI组件树 |
装饰器(Decorator) | 动态添加职责 | 嵌套包装,不修改原类 | 输入/输出流增强、中间件 |
外观(Facade) | 简化复杂子系统的接口 | 提供统一入口,隐藏内部细节 | 框架启动器、复杂API封装 |
桥接(Bridge) | 分离抽象与实现 | 避免多层继承,独立变化维度 | 跨平台渲染、设备驱动 |
代理(Proxy) | 控制对其他对象的访问 | 间接访问,添加额外逻辑 | 延迟加载、访问控制、远程调用 |
享元/蝇量(Flyweight) | 共享细粒度对象以减少内存 | 分离内部状态(共享)和外部状态(独享) | 文本编辑器字符、游戏粒子系统 |
三、行为型模式(11种)
模式 | 核心目的 | 关键特点 | 典型应用场景 |
---|---|---|---|
策略(Strategy) | 封装可互换算法族 | 消除条件语句,运行时切换算法 | 支付方式、排序算法选择 |
观察者(Observer) | 一对多依赖:状态变化通知所有观察者 | 松耦合,广播通知 | 事件处理、实时数据推送 |
命令(Command) | 将请求封装为对象 | 支持参数化、队列、撤销操作 | 事务管理、操作历史记录 |
迭代器(Iterator) | 顺序访问聚合对象元素 | 分离集合结构和遍历算法 | 集合遍历、自定义迭代 |
状态(State) | 对象内部状态改变时改变行为 | 消除状态条件判断,封装状态转移逻辑 | 订单流程、游戏角色状态 |
模板方法(Template Method) | 定义算法骨架,步骤延迟到子类 | 复用算法结构,子类重写特定步骤 | 框架钩子、标准化流程 |
中介者(Mediator) | 集中管理对象间通信 | 减少对象间直接依赖,简化交互 | 聊天室、空中交通管制 |
访问者(Visitor) | 在不修改类的前提下添加新操作 | 分离算法与对象结构 | 文档导出、语法树分析 |
解释器(Interpreter) | 定义语法的表示并解释句子 | 语法树结构,扩展文法方便 | 正则表达式、SQL解析 |
职责链/责任链(Chain of Responsibility) | 多个对象依次处理请求 | 动态组合处理链,解耦发送者和接收者 | 审批流程、异常处理管道 |
备忘录(Memento) | 捕获对象状态以便恢复 | 状态保存与恢复,不破坏封装性 | 游戏存档、撤销操作 |
核心异同点对比
1. 模式类型差异
模式类型 | 解决核心问题 | 关键区别 |
---|---|---|
创建型 | 对象创建机制 | 控制实例化过程 |
结构型 | 对象/类组合方式 | 构建灵活高效的结构 |
行为型 | 对象间职责分配与通信 | 管理运行时交互流程 |
2. 相似模式对比
对比组 | 核心区别 |
---|---|
工厂方法 vs 抽象工厂 | 工厂方法处理单一产品,抽象工厂处理产品家族 |
适配器 vs 代理 | 适配器解决接口兼容问题,代理控制访问过程 |
策略 vs 状态 | 策略主动切换算法,状态随对象内部状态自动变化 |
装饰器 vs 责任链 | 装饰器静态增强对象功能,责任链动态传递请求 |
观察者 vs 中介者 | 观察者直接广播通知,中介者集中协调对象交互 |
命令 vs 备忘录 | 命令封装操作请求,备忘录保存对象状态 |
迭代器 vs 访问者 | 迭代器遍历集合元素,访问者对元素执行操作 |
模板方法 vs 策略 | 模板方法用继承定义算法骨架,策略用组合切换算法 |
3. 设计原则映射
设计原则 | 典型体现模式 | 模式作用 |
---|---|---|
开闭原则 | 策略、观察者、装饰器、访问者 | 扩展开放,修改关闭 |
单一职责 | 命令、状态、迭代器 | 每个类/模式专注单一功能 |
接口隔离 | 适配器、外观、代理 | 提供精简专用接口 |
依赖倒置 | 工厂方法、抽象工厂、策略 | 依赖抽象而非具体实现 |
迪米特法则 | 中介者、外观 | 减少对象间依赖 |
合成复用原则 | 桥接、组合、装饰器、享元 | 优先使用组合而非继承 |
模式速查表(关键区分点)
模式 | 类型 | 核心特征 | 典型场景 | 示例关键代码 |
---|---|---|---|---|
单例 | 创建型 | 全局唯一实例 | 配置管理 | if not cls._instance: ... |
工厂方法 | 创建型 | 子类决定对象 | 跨平台组件 | create_xxx() |
抽象工厂 | 创建型 | 创建产品家族 | UI主题系统 | create_button()+create_menu() |
建造者 | 创建型 | 分步构建复杂对象 | 餐品定制 | add_part().build() |
原型 | 创建型 | 克隆对象 | 游戏实体复制 | copy.deepcopy() |
适配器 | 结构型 | 接口转换 | 旧系统集成 | Adapter(old_sys).request() |
桥接 | 结构型 | 分离抽象/实现 | 跨平台渲染 | Shape(Renderer()) |
组合 | 结构型 | 树形结构统一处理 | 文件系统 | folder.add(file) |
装饰器 | 结构型 | 嵌套功能增强 | 中间件管道 | LoggingDecorator(service) |
外观 | 结构型 | 简化复杂系统接口 | 框架启动器 | Facade().boot() |
享元 | 结构型 | 共享对象减少内存 | 游戏粒子系统 | Factory.get_tree_type() |
代理 | 结构型 | 控制对象访问 | 延迟加载 | Proxy().request() |
职责链 | 行为型 | 请求链式传递 | 审批流程 | handler.set_next(next) |
命令 | 行为型 | 封装操作为对象 | 撤销/重做 | Command().execute() |
解释器 | 行为型 | 解释语法 | 规则引擎 | Expression().interpret() |
迭代器 | 行为型 | 遍历集合 | 自定义集合 | __iter__() |
中介者 | 行为型 | 集中对象通信 | 聊天室 | Mediator.send(msg) |
备忘录 | 行为型 | 保存/恢复状态 | 游戏存档 | Editor.save() |
观察者 | 行为型 | 状态变化通知 | 事件处理 | Subject.attach(obs) |
状态 | 行为型 | 状态改变行为 | 订单流程 | context.state.handle() |
策略 | 行为型 | 互换算法 | 支付方式选择 | Context(Strategy()) |
模板方法 | 行为型 | 算法骨架+子类实现 | 标准化流程 | template.generate() |
访问者 | 行为型 | 添加操作不改类 | 文档导出 | element.accept(visitor) |
使用场景速查表
需求场景 | 首选模式 | 备选模式 | 原因说明 |
---|---|---|---|
全局唯一资源访问 | 单例 | - | 强制唯一实例 |
跨平台UI组件创建 | 抽象工厂 | 工厂方法 | 需要配套组件 |
分步骤构建复杂对象 | 建造者 | 工厂方法 | 构造过程复杂 |
动态添加日志/权限控制 | 装饰器 | 代理 | 透明增强功能 |
游戏/文档对象克隆 | 原型 | 工厂方法 | 避免初始化开销 |
状态驱动的行为变化 | 状态 | 策略 | 行为随内部状态自动变化 |
操作撤销/重做功能 | 命令+备忘录 | - | 需要保存状态历史 |
事件通知机制 | 观察者 | 发布-订阅 | 解耦事件源和处理者 |
集合元素遍历 | 迭代器 | 访问者 | 分离遍历算法 |
跨系统接口兼容 | 适配器 | 外观 | 转换旧接口 |
算法灵活切换 | 策略 | 模板方法 | 运行时选择算法 |
复杂审批流程 | 职责链 | 状态 | 动态传递请求 |
对象结构统一操作 | 访问者 | 迭代器 | 添加新操作不改结构 |
代码实现对比
创建型模式(处理对象创建机制)
1. 工厂方法模式(Factory Method)
python
from abc import ABC, abstractmethod
class Button(ABC):
@abstractmethod
def render(self): pass
class WindowsButton(Button):
def render(self):
return "Windows风格按钮"
class WebButton(Button):
def render(self):
return "Web风格按钮"
# 核心:通过子类决定创建的对象类型
class UIFactory(ABC):
@abstractmethod
def create_button(self) -> Button: pass
class WindowsUIFactory(UIFactory):
def create_button(self):
return WindowsButton() # 专注于Windows对象创建
class WebUIFactory(UIFactory):
def create_button(self):
return WebButton() # 专注于Web对象创建
# 使用
factory = WebUIFactory()
button = factory.create_button()
print(button.render()) # 输出: Web风格按钮
重点:将对象创建延迟到子类,避免客户端与具体类耦合。
2. 抽象工厂模式(Abstract Factory)
python
class TextBox(ABC): # 抽象产品A
@abstractmethod
def display(self): pass
class DarkTextBox(TextBox):
def display(self):
return "深色文本框"
class LightTextBox(TextBox):
def display(self):
return "浅色文本框"
# 核心:创建相关对象家族
class ThemeFactory(ABC):
@abstractmethod
def create_button(self) -> Button: pass
@abstractmethod
def create_textbox(self) -> TextBox: pass # 新增产品线
class DarkThemeFactory(ThemeFactory):
def create_button(self):
return DarkButton() # 创建配套的深色系组件
def create_textbox(self):
return DarkTextBox() # 保持风格一致
# 客户端只需切换工厂即可改变整套UI
factory = DarkThemeFactory()
print(factory.create_button().render(), factory.create_textbox().display())
重点:创建一组相关/依赖对象,确保兼容性。
3. 单例模式(Singleton)
python
class AppConfig:
_instance = None
# 核心:控制实例化过程
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
cls._instance.load_config() # 初始化配置
return cls._instance
def load_config(self):
self.settings = {"theme": "dark", "language": "zh"}
# 使用
config1 = AppConfig()
config2 = AppConfig()
print(config1 is config2) # 输出: True (同一个对象)
重点:全局唯一访问点,避免重复创建消耗资源。
4. 建造者模式(Builder)
python
class Computer:
def __init__(self):
self.ram = None
self.storage = None
self.gpu = None
def __str__(self):
return f"配置: RAM={self.ram}GB, 存储={self.storage}GB, GPU={self.gpu}"
# 核心:分离复杂对象的构建和表示
class ComputerBuilder:
def __init__(self):
self.computer = Computer()
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 build(self):
return self.computer # 返回最终产品
# 使用
builder = ComputerBuilder()
high_end_pc = (builder.set_ram(32)
.set_storage(1000)
.set_gpu("RTX 4090")
.build())
print(high_end_pc) # 配置: RAM=32GB, 存储=1000GB, GPU=RTX 4090
重点:分步骤构建复杂对象,相同构建过程可创建不同表示
5. 原型模式(Prototype)
python
import copy
class Shape:
def __init__(self, color):
self.color = color
def clone(self):
# 核心:通过深拷贝实现对象克隆
return copy.deepcopy(self)
def render(self):
return f"渲染{self.color}色的{self.__class__.__name__}"
class Circle(Shape):
def __init__(self, color, radius):
super().__init__(color)
self.radius = radius
# 使用
original = Circle("红", 10)
clone = original.clone() # 克隆对象
clone.color = "蓝" # 修改克隆体属性
print(original.render()) # 渲染红色的Circle
print(clone.render()) # 渲染蓝色的Circle
重点:通过克隆而非新建创建对象,避免昂贵的初始化过程
结构型模式(处理对象组合)
6. 适配器模式(Adapter)
python
class OldService: # 不兼容的旧接口
def specific_request(self):
return "旧系统数据"
class Adapter:
def __init__(self, old_service):
self._old_service = old_service
# 核心:转换接口形式
def request(self):
data = self._old_service.specific_request()
return f"适配后的数据: {data}"
# 客户端使用统一接口
adapter = Adapter(OldService())
print(adapter.request()) # 输出: 适配后的数据: 旧系统数据
重点:充当中间层转换接口,解决兼容性问题。
7. 装饰器模式(Decorator)
python
class Coffee: # 基础组件
def cost(self):
return 10
# 核心:动态添加功能
class CoffeeDecorator:
def __init__(self, coffee):
self._coffee = coffee
def cost(self):
return self._coffee.cost()
class MilkDecorator(CoffeeDecorator):
def cost(self):
return super().cost() + 2 # 增加牛奶费用
class SugarDecorator(CoffeeDecorator):
def cost(self):
return super().cost() + 1 # 增加糖费用
# 使用
coffee = Coffee()
coffee = MilkDecorator(coffee) # 装饰牛奶
coffee = SugarDecorator(coffee) # 再装饰糖
print(coffee.cost()) # 输出: 13
重点:运行时扩展对象功能,避免子类爆炸。
8. 桥接模式(Bridge)
python
class Renderer(ABC): # 实现抽象
@abstractmethod
def render_circle(self, radius): pass
class VectorRenderer(Renderer):
def render_circle(self, radius):
print(f"绘制矢量圆,半径={radius}") # 矢量渲染实现
class RasterRenderer(Renderer):
def render_circle(self, radius):
print(f"绘制像素圆,半径={radius}") # 栅格渲染实现
# 核心:分离抽象和实现,使两者可独立变化
class Shape:
def __init__(self, renderer):
self.renderer = renderer # 组合实现对象
def draw(self): pass
class Circle(Shape):
def __init__(self, renderer, radius):
super().__init__(renderer)
self.radius = radius
def draw(self):
self.renderer.render_circle(self.radius) # 委托给实现
# 使用
vector_circle = Circle(VectorRenderer(), 5)
vector_circle.draw() # 绘制矢量圆,半径=5
raster_circle = Circle(RasterRenderer(), 10)
raster_circle.draw() # 绘制像素圆,半径=10
重点:解耦抽象和实现,支持多维度扩展
9. 组合模式(Composite)
python
class FileSystemComponent(ABC): # 统一接口
@abstractmethod
def display(self, indent=0): pass
class File(FileSystemComponent):
def __init__(self, name):
self.name = name
def display(self, indent=0):
print(' ' * indent + f"📄 {self.name}")
# 核心:以树形结构处理对象集合
class Directory(FileSystemComponent):
def __init__(self, name):
self.name = name
self.children = [] # 可包含其他组件
def add(self, component):
self.children.append(component)
def display(self, indent=0):
print(' ' * indent + f"📁 {self.name}")
for child in self.children:
child.display(indent + 2) # 递归调用
# 使用
root = Directory("根目录")
docs = Directory("文档")
docs.add(File("报告.doc"))
root.add(docs)
root.add(File("README.txt"))
root.display()
# 输出:
# 📁 根目录
# 📁 文档
# 📄 报告.doc
# 📄 README.txt
重点:统一处理单个对象和对象集合,实现递归结构
10. 外观模式(Facade)
python
class CPU:
def process(self):
return "处理数据"
class Memory:
def load(self):
return "加载内存"
class HardDrive:
def read(self):
return "读取硬盘"
# 核心:提供统一简化接口
class ComputerFacade:
def __init__(self):
self.cpu = CPU()
self.memory = Memory()
self.hd = HardDrive()
def start(self):
results = []
results.append(self.hd.read())
results.append(self.memory.load())
results.append(self.cpu.process())
return " | ".join(results)
# 使用
computer = ComputerFacade()
print(computer.start()) # 读取硬盘 | 加载内存 | 处理数据
重点:为复杂子系统提供统一入口,隐藏内部复杂性
11. 享元模式(Flyweight)
python
class TreeType:
def __init__(self, name, color):
# 核心:共享内在状态
self.name = name
self.color = color
def display(self, x, y):
return f"在({x},{y})显示{self.color}的{self.name}"
class TreeFactory:
_tree_types = {}
@classmethod
def get_tree_type(cls, name, color):
key = f"{name}_{color}"
if key not in cls._tree_types:
cls._tree_types[key] = TreeType(name, color)
return cls._tree_types[key]
class Tree:
def __init__(self, x, y, tree_type):
# 存储外在状态
self.x = x
self.y = y
self.type = tree_type # 共享内在状态
def display(self):
return self.type.display(self.x, self.y)
# 使用
forest = []
factory = TreeFactory()
# 创建10000棵树,但只有2种类型
for i in range(10000):
# 交替使用两种树类型
tree_type = factory.get_tree_type("橡树", "绿") if i % 2 == 0 else factory.get_tree_type("松树", "深绿")
forest.append(Tree(i, i*10, tree_type))
print(forest[0].display()) # 在(0,0)显示绿的橡树
print(f"总树类型数: {len(factory._tree_types)}") # 输出: 总树类型数: 2
重点:通过共享相似对象减少内存使用
20. 代理模式 (Proxy)
python
class RealDatabase:
"""真实数据库对象(创建成本高)"""
def query(self, sql):
print(f"执行SQL查询: {sql}")
return "查询结果"
class DatabaseProxy:
"""数据库代理(控制对真实对象的访问)"""
def __init__(self):
self._real_db = None
self._cache = {}
def query(self, sql):
# 核心:延迟创建真实对象直到需要时
if self._real_db is None:
print("初始化真实数据库连接...")
self._real_db = RealDatabase()
# 添加缓存功能
if sql in self._cache:
print(f"从缓存获取结果: {sql}")
return self._cache[sql]
# 委托给真实对象
result = self._real_db.query(sql)
self._cache[sql] = result
return result
# 使用
db = DatabaseProxy()
print(db.query("SELECT * FROM users")) # 首次查询初始化数据库
print(db.query("SELECT * FROM users")) # 第二次查询使用缓存
重点:控制对真实对象的访问,常用于延迟加载、访问控制、缓存等场景
行为型模式(处理对象间通信)
12. 观察者模式(Observer)
python
class NewsPublisher: # 主题
def __init__(self):
self._subscribers = []
self._latest_news = None
# 核心:管理订阅者列表
def attach(self, subscriber):
self._subscribers.append(subscriber)
def notify(self):
for sub in self._subscribers:
sub.update(self._latest_news) # 推送更新
def publish_news(self, news):
self._latest_news = news
self.notify() # 状态变化时通知
class Subscriber:
def update(self, news):
print(f"收到新闻: {news}")
# 使用
publisher = NewsPublisher()
publisher.attach(Subscriber())
publisher.publish_news("Python 4.0发布!") # 自动通知所有订阅者
重点:实现发布-订阅机制,解耦主题和观察者。
13. 策略模式(Strategy)
python
class PaymentStrategy(ABC): # 策略接口
@abstractmethod
def pay(self, amount): pass
class CreditCardPayment(PaymentStrategy):
def pay(self, amount):
print(f"信用卡支付: {amount}元")
class AlipayPayment(PaymentStrategy):
def pay(self, amount):
print(f"支付宝支付: {amount}元")
# 核心:运行时切换算法
class PaymentContext:
def __init__(self, strategy: PaymentStrategy):
self._strategy = strategy
def execute_payment(self, amount):
self._strategy.pay(amount) # 委托给具体策略
# 使用
context = PaymentContext(CreditCardPayment())
context.execute_payment(100) # 输出: 信用卡支付: 100元
context = PaymentContext(AlipayPayment()) # 动态切换策略
context.execute_payment(200) # 输出: 支付宝支付: 200元
重点:封装可互换的算法族,消除条件分支。#### 11. 备忘录模式(Memento)
python
class EditorState: # 备忘录
def __init__(self, content):
self.content = content
class Editor: # 原发器
def __init__(self):
self.content = ""
def type(self, text):
self.content += text
# 核心:创建状态快照
def save(self) -> EditorState:
return EditorState(self.content)
# 恢复状态
def restore(self, state: EditorState):
self.content = state.content
# 管理者
class History:
def __init__(self):
self.states = [] # 存储状态历史
def push(self, state):
self.states.append(state)
def pop(self):
return self.states.pop()
# 使用
editor = Editor()
history = History()
editor.type("Hello")
history.push(editor.save()) # 保存状态1
editor.type(" World!")
print(editor.content) # "Hello World!"
# 撤销操作
editor.restore(history.pop())
print(editor.content) # "Hello"
重点:捕获并外部化对象状态,支持撤销操作
14. 访问者模式(Visitor)
python
class DocumentElement(ABC):
@abstractmethod
def accept(self, visitor): pass # 核心:接收访问者
class TextElement(DocumentElement):
def __init__(self, text):
self.text = text
def accept(self, visitor):
visitor.visit_text(self) # 分派给具体访问方法
class ImageElement(DocumentElement):
def __init__(self, path):
self.path = path
def accept(self, visitor):
visitor.visit_image(self)
# 访问者接口
class Visitor(ABC):
@abstractmethod
def visit_text(self, element): pass
@abstractmethod
def visit_image(self, element): pass
# 具体访问者实现
class ExportVisitor(Visitor):
def visit_text(self, element):
print(f"导出文本: '{element.text}'")
def visit_image(self, element):
print(f"导出图片: {element.path}")
# 使用
document = [TextElement("欢迎"), ImageElement("logo.png")]
visitor = ExportVisitor()
for element in document:
element.accept(visitor) # 输出:
# 导出文本: '欢迎'
# 导出图片: logo.png
重点:将操作与对象结构分离,便于新增操作
15. 中介者模式(Mediator)
python
class AirTrafficControl: # 中介者
def __init__(self):
self.aircrafts = []
# 核心:协调对象间通信
def register(self, aircraft):
self.aircrafts.append(aircraft)
aircraft.atc = self
def request_landing(self, requester):
print(f"塔台收到 {requester} 降落请求")
for craft in self.aircrafts:
if craft != requester:
print(f"通知 {craft}: {requester} 正在降落")
class Aircraft:
def __init__(self, callsign):
self.callsign = callsign
self.atc = None
def request_land(self):
self.atc.request_landing(self) # 通过中介者通信
def __str__(self):
return self.callsign
# 使用
atc = AirTrafficControl()
flight1 = Aircraft("CX888")
flight2 = Aircraft("UA919")
atc.register(flight1)
atc.register(flight2)
flight1.request_land()
# 输出:
# 塔台收到 CX888 降落请求
# 通知 UA919: CX888 正在降落
重点:集中管理对象间通信,减少网状依赖
16. 模板方法模式(Template Method)
python
from abc import ABC, abstractmethod
class DataProcessor(ABC):
# 核心:定义算法骨架
def process(self):
self.load_data()
self.clean_data()
self.analyze()
self.report()
def load_data(self):
print("加载数据...")
def clean_data(self):
print("清洗数据...")
@abstractmethod
def analyze(self): pass
def report(self):
print("生成报告...")
class SalesProcessor(DataProcessor):
def analyze(self):
print("执行销售数据分析") # 具体实现
class InventoryProcessor(DataProcessor):
def analyze(self):
print("执行库存数据分析") # 具体实现
# 使用
sales = SalesProcessor()
sales.process() # 加载数据...清洗数据...执行销售数据分析...生成报告...
重点:父类定义算法框架,子类实现具体步骤
17. 状态模式(State)
python
class DocumentState(ABC):
@abstractmethod
def publish(self, document): pass
class DraftState(DocumentState):
def publish(self, document):
print("发布草稿 -> 转为审核状态")
document.state = ReviewState()
class ReviewState(DocumentState):
def publish(self, document):
if document.approved:
print("审核通过 -> 转为发布状态")
document.state = PublishedState()
else:
print("审核未通过 -> 返回草稿状态")
document.state = DraftState()
class PublishedState(DocumentState):
def publish(self, document):
print("文档已发布,无需再次发布")
# 核心:状态对象改变行为
class Document:
def __init__(self):
self.state = DraftState() # 初始状态
self.approved = False
def publish(self):
self.state.publish(self) # 委托给状态对象
# 使用
doc = Document()
doc.publish() # 发布草稿 -> 转为审核状态
doc.approved = True
doc.publish() # 审核通过 -> 转为发布状态
doc.publish() # 文档已发布,无需再次发布
重点:封装状态相关行为,状态改变导致行为改变
18. 责任链模式(Chain of Responsibility)
python
class Handler(ABC):
def __init__(self, successor=None):
self._successor = successor
def handle(self, request):
# 核心:沿链传递请求
if self.can_handle(request):
return self._process(request)
elif self._successor:
return self._successor.handle(request)
else:
return None
@abstractmethod
def can_handle(self, request): pass
@abstractmethod
def _process(self, request): pass
class Level1Support(Handler):
def can_handle(self, request):
return request == "简单问题"
def _process(self, request):
return "一级支持处理了问题"
class Level2Support(Handler):
def can_handle(self, request):
return request == "复杂问题"
def _process(self, request):
return "二级支持处理了问题"
class Level3Support(Handler):
def can_handle(self, request):
return request == "严重问题"
def _process(self, request):
return "三级支持处理了问题"
# 构建责任链
support = Level1Support(Level2Support(Level3Support()))
# 使用
print(support.handle("简单问题")) # 一级支持处理了问题
print(support.handle("严重问题")) # 三级支持处理了问题
重点:解耦请求发送者和接收者,允许多个对象处理请求
19. 命令模式(Command)
python
class Command(ABC):
@abstractmethod
def execute(self): pass
class LightOnCommand(Command):
def __init__(self, light):
self.light = light
def execute(self):
self.light.turn_on()
class LightOffCommand(Command):
def __init__(self, light):
self.light = light
def execute(self):
self.light.turn_off()
# 接收者
class Light:
def turn_on(self):
print("开灯")
def turn_off(self):
print("关灯")
# 调用者
class RemoteControl:
def __init__(self):
self._commands = {}
def register(self, name, command):
self._commands[name] = command
def press(self, name):
if name in self._commands:
self._commands[name].execute()
# 使用
light = Light()
remote = RemoteControl()
remote.register("on", LightOnCommand(light))
remote.register("off", LightOffCommand(light))
remote.press("on") # 开灯
remote.press("off") # 关灯
重点:将请求封装为对象,支持撤销、队列和日志操作
21. 迭代器模式 (Iterator)
python
class BookCollection:
"""自定义集合类"""
def __init__(self):
self._books = []
self._index = 0
def add_book(self, title):
self._books.append(title)
def __iter__(self):
# 核心:返回迭代器对象
return self.BookIterator(self._books)
class BookIterator:
"""内部迭代器类"""
def __init__(self, books):
self._books = books
self._index = 0
def __next__(self):
# 核心:实现迭代协议
if self._index < len(self._books):
result = self._books[self._index]
self._index += 1
return result
raise StopIteration
# 使用
library = BookCollection()
library.add_book("Python设计模式")
library.add_book("代码大全")
library.add_book("重构")
# 通过迭代器遍历
print("图书馆藏书:")
for book in library:
print(f"- {book}")
重点:提供统一接口遍历集合元素,隐藏底层数据结构
22. 解释器模式 (Interpreter)
python
from abc import ABC, abstractmethod
class Context:
"""上下文存储变量值"""
def __init__(self):
self.variables = {}
class Expression(ABC):
"""抽象表达式"""
@abstractmethod
def interpret(self, context): pass
class Number(Expression):
"""终结符表达式:数字"""
def __init__(self, value):
self.value = value
def interpret(self, context):
return self.value
class Variable(Expression):
"""终结符表达式:变量"""
def __init__(self, name):
self.name = name
def interpret(self, context):
return context.variables[self.name]
class Add(Expression):
"""非终结符表达式:加法"""
def __init__(self, left, right):
self.left = left
self.right = right
def interpret(self, context):
# 核心:递归解释子表达式
return self.left.interpret(context) + self.right.interpret(context)
# 使用
context = Context()
context.variables = {'x': 5, 'y': 10}
# 构建表达式树:x + (y + 3)
expression = Add(
Variable('x'),
Add(Variable('y'), Number(3))
)
result = expression.interpret(context)
print(f"表达式结果: {result}") # 输出: 18
重点:定义语言的文法,用于解释特定领域语言(DSL)
23. 备忘录模式 (Memento Pattern)
python
class EditorState:
"""备忘录类:存储编辑器的状态快照"""
def __init__(self, content, cursor_position, selection):
# 核心:存储需要恢复的状态
self.content = content
self.cursor_position = cursor_position
self.selection = selection # 选中的文本范围
def __str__(self):
return f"状态[内容: '{self.content[:10]}...', 光标位置: {self.cursor_position}]"
class Editor:
"""原发器类:创建备忘录并可从备忘录恢复状态"""
def __init__(self):
self.content = ""
self.cursor_position = 0
self.selection = None
def type_text(self, text):
"""输入文本并更新光标位置"""
if self.selection:
# 替换选中文本
start, end = self.selection
self.content = self.content[:start] + text + self.content[end:]
self.cursor_position = start + len(text)
self.selection = None
else:
# 在光标处插入文本
self.content = self.content[:self.cursor_position] + text + self.content[self.cursor_position:]
self.cursor_position += len(text)
def set_selection(self, start, end):
"""设置文本选择范围"""
self.selection = (start, end)
self.cursor_position = end # 光标移动到选择结束位置
def create_state(self) -> EditorState:
"""创建状态快照(备忘录)"""
# 核心:捕获当前状态
return EditorState(
content=self.content,
cursor_position=self.cursor_position,
selection=self.selection
)
def restore_state(self, state: EditorState):
"""从备忘录恢复状态"""
# 核心:恢复保存的状态
self.content = state.content
self.cursor_position = state.cursor_position
self.selection = state.selection
def __str__(self):
return f"编辑器[内容: '{self.content[:10]}...', 光标: {self.cursor_position}]"
class History:
"""管理者类:负责存储和管理备忘录"""
def __init__(self):
self._states = [] # 存储状态历史
self._current_index = -1 # 当前状态索引
def save_state(self, state: EditorState):
"""保存新状态并截断之后的撤销历史"""
# 当有新的状态时,删除当前索引之后的所有状态
self._states = self._states[:self._current_index + 1]
self._states.append(state)
self._current_index = len(self._states) - 1
print(f"保存状态: {state}")
def undo(self) -> EditorState:
"""撤销:返回上一个状态"""
if self._current_index > 0:
self._current_index -= 1
state = self._states[self._current_index]
print(f"撤销到: {state}")
return state
print("无法撤销:已在最初状态")
return None
def redo(self) -> EditorState:
"""重做:返回下一个状态"""
if self._current_index < len(self._states) - 1:
self._current_index += 1
state = self._states[self._current_index]
print(f"重做到: {state}")
return state
print("无法重做:已在最新状态")
return None
def show_history(self):
"""显示历史状态(调试用)"""
print("\n历史记录:")
for i, state in enumerate(self._states):
prefix = "-> " if i == self._current_index else " "
print(f"{prefix}[{i}] {state}")
# 使用示例
if __name__ == "__main__":
editor = Editor()
history = History()
# 初始编辑
editor.type_text("设计模式")
history.save_state(editor.create_state())
# 继续编辑
editor.type_text("很重要")
history.save_state(editor.create_state())
# 选择文本并替换
editor.set_selection(0, 2) # 选择前两个字符
editor.type_text("编程") # 替换选中文本
history.save_state(editor.create_state())
print(f"\n当前状态: {editor}")
# 显示历史
history.show_history()
# 执行撤销
print("\n执行撤销操作...")
editor.restore_state(history.undo())
print(f"撤销后状态: {editor}")
# 再次撤销
print("\n再次撤销...")
editor.restore_state(history.undo())
print(f"撤销后状态: {editor}")
# 执行重做
print("\n执行重做操作...")
editor.restore_state(history.redo())
print(f"重做后状态: {editor}")
# 添加新内容(会截断后续历史)
print("\n添加新内容...")
editor.type_text("!")
history.save_state(editor.create_state())
history.show_history()