行为型模式
约 1076 字大约 4 分钟
设计模式行为型模式
2026-04-14
概述
行为型模式关注对象之间的通信和职责分配。
模式分类
| 模式 | 描述 |
|---|---|
| 责任链模式 | 多个对象处理请求 |
| 命令模式 | 请求封装为对象 |
| 迭代器模式 | 顺序访问集合 |
| 中介者模式 | 对象间接通信 |
| 备忘录模式 | 保存状态 |
| 观察者模式 | 一对多依赖 |
| 状态模式 | 状态决定行为 |
| 策略模式 | 算法可替换 |
| 模板方法模式 | 骨架 + 子类实现 |
| 访问者模式 | 操作与结构分离 |
观察者模式 (Observer)
定义对象间的一种一对多的依赖关系。
class Observer {
update() {}
}
class Subject {
constructor() {
this.observers = [];
}
attach(observer) {
this.observers.push(observer);
}
detach(observer) {
const index = this.observers.indexOf(observer);
if (index > -1) {
this.observers.splice(index, 1);
}
}
notify() {
this.observers.forEach(o => o.update());
}
}应用场景
- 事件处理系统
- MVC 架构
- 数据绑定
策略模式 (Strategy)
定义一系列的算法,把它们一个个封装起来,并且使它们可相互替换。
class Strategy {
execute(data) {
throw new Error('必须实现');
}
}
class ConcreteStrategyA extends Strategy {
execute(data) {
return data.map(x => x * 2);
}
}
class ConcreteStrategyB extends Strategy {
execute(data) {
return data.filter(x => x > 5);
}
}
class Context {
constructor(strategy) {
this.strategy = strategy;
}
setStrategy(strategy) {
this.strategy = strategy;
}
executeStrategy(data) {
return this.strategy.execute(data);
}
}应用场景
- 算法切换
- 表单验证
命令模式 (Command)
将请求封装成对象,从而使可用不同的请求对客户进行参数化。
class Command {
execute() {
throw new Error('必须实现');
}
}
class ConcreteCommand extends Command {
constructor(receiver) {
super();
this.receiver = receiver;
}
execute() {
this.receiver.action();
}
}
class Invoker {
constructor(command) {
this.command = command;
}
invoke() {
return this.command.execute();
}
}应用场景
- 撤销/重做
- 宏命令
- 异步任务队列
模板方法模式 (Template Method)
定义一个算法的骨架,将一些步骤延迟到子类中。
class AbstractClass {
templateMethod() {
this.step1();
this.step2();
this.step3();
}
step1() {
throw new Error('必须实现');
}
step2() {
throw new Error('必须实现');
}
step3() {}
}
class ConcreteClass extends AbstractClass {
step1() {
console.log('Step 1');
}
step2() {
console.log('Step 2');
}
}应用场景
- 框架钩子
- 算法骨架固定
迭代器模式 (Iterator)
提供一种方法顺序访问一个集合对象中的各个元素。
class Iterator {
constructor(collection) {
this.collection = collection;
this.index = 0;
}
hasNext() {
return this.index < this.collection.length;
}
next() {
if (this.hasNext()) {
return this.collection[this.index++];
}
return null;
}
}
class Collection {
constructor() {
this.items = [];
}
add(item) {
this.items.push(item);
}
createIterator() {
return new Iterator(this.items);
}
}应用场景
- 统一遍历接口
- 延迟迭代
职责链模式 (Chain of Responsibility)
将对象连成一条链,并沿着这条链传递请求。
class Handler {
constructor() {
this.nextHandler = null;
}
setNext(handler) {
this.nextHandler = handler;
return handler;
}
handle(request) {
if (this.nextHandler) {
return this.nextHandler.handle(request);
}
return null;
}
}
class ConcreteHandler1 extends Handler {
handle(request) {
if (request === 'type1') {
return 'Handler1 处理';
}
return super.handle(request);
}
}应用场景
- 审批流程
- 事件处理
状态模式 (State)
允许对象在内部状态改变时改变它的行为。
class State {
handle(context) {
throw new Error('必须实现');
}
}
class ConcreteStateA extends State {
handle(context) {
context.setState(new ConcreteStateB());
}
}
class ConcreteStateB extends State {
handle(context) {
context.setState(new ConcreteStateA());
}
}
class Context {
constructor(state) {
this.state = state;
}
setState(state) {
this.state = state;
}
request() {
this.state.handle(this);
}
}应用场景
- 状态机
- 工作流
中介者模式 (Mediator)
用一个中介对象来封装一系列的对象交互。
class Mediator {
notify(sender, event) {
throw new Error('必须实现');
}
}
class ConcreteMediator extends Mediator {
constructor(component1, component2) {
super();
this.component1 = component1;
this.component2 = component2;
}
notify(sender, event) {
if (event === 'A') {
this.component2.doSomething();
}
if (event === 'B') {
this.component1.doSomething();
}
}
}应用场景
- GUI 组件通信
- 解耦对象
备忘录模式 (Memento)
在不破坏封装性的前提下,捕获对象的内部状态。
class Memento {
constructor(state) {
this.state = state;
}
getState() {
return this.state;
}
}
class Originator {
constructor(state) {
this.state = state;
}
save() {
return new Memento(this.state);
}
restore(memento) {
this.state = memento.getState();
}
}
class Caretaker {
constructor(originator) {
this.originator = originator;
this.mementos = [];
}
backup() {
this.mementos.push(this.originator.save());
}
undo() {
if (this.mementos.length) {
this.originator.restore(this.mementos.pop());
}
}
}应用场景
- 撤销功能
- 快照
访问者模式 (Visitor)
表示一个作用于某对象结构中的各元素的操作。
class Visitor {
visitElementA(element) {
throw new Error('必须实现');
}
visitElementB(element) {
throw new Error('必须实现');
}
}
class ConcreteVisitor extends Visitor {
visitElementA(element) {
return element.operationA();
}
visitElementB(element) {
return element.operationB();
}
}
class Element {
accept(visitor) {
throw new Error('必须实现');
}
}
class ElementA extends Element {
accept(visitor) {
return visitor.visitElementA(this);
}
operationA() {
return 'ElementA';
}
}应用场景
- 操作与结构分离
- 添加新操作
模式对比
| 模式 | 核心思想 | 通信方式 |
|---|---|---|
| 观察者 | 一对多通知 | 直接通知 |
| 策略 | 算法封装 | 上下文切换 |
| 命令 | 请求封装 | 调用者执行 |
| 模板方法 | 骨架复用 | 继承 |
| 迭代器 | 顺序访问 | 游标 |
| 职责链 | 链式处理 | 传递 |
| 状态 | 状态转换 | 自动切换 |
| 中介者 | 间接通信 | 中心协调 |
| 备忘录 | 状态保存 | caretaker |
| 访问者 | 操作分离 | 双分派 |
