程序员成长为架构师之路
第4篇(下)|行为型设计模式沉浸式理解:把业务流程写成套路
“行为型模式不是教你写代码,
是教你怎么组织对象之间的行为关系。”
——会写逻辑的是程序员,会写模式的是架构师
🔍 一、行为型设计模式简介
行为型模式关注的是:
“对象之间如何协作,共同完成任务”,而不是它们自身的结构。
它像流程编排师,让模块之间的协作解耦、灵活、可扩展。
🧭 二、行为型模式一览表
| 模式 | 场景 | 核心作用 |
|---|---|---|
| 策略模式 | 多种算法/行为 | 可切换的“策略” |
| 模板方法 | 统一流程,自定义细节 | 基类定义框架,子类填空 |
| 观察者 | 发布-订阅通知 | 多方监听,通知响应 |
| 责任链 | 多处理节点按顺序处理 | 解耦请求与处理者 |
| 状态模式 | 对象状态行为变化 | 状态驱动行为 |
| 命令模式 | 将请求封装为对象 | 请求可记录、回滚 |
| 解释器模式 | 自定义语言或表达式解析 | 文法规则驱动行为 |
| 备忘录模式 | 保存历史状态 | 实现撤销/恢复 |
| 中介者模式 | 控制对象间通信 | 解耦组件间关系 |
| 访问者模式 | 对象结构不变,行为扩展 | 统一操作多个类 |
| 迭代器模式 | 顺序访问集合元素 | 统一遍历逻辑 |
🌟 1. 策略模式(Strategy)—— 用“套路”解耦算法
场景:
- 多种可互换算法:排序、折扣计算、支付方式
- 策略可热切换,不影响主流程
Java 示例:
interface PayStrategy {
void pay();
}
class Alipay implements PayStrategy {
public void pay() { System.out.println("使用支付宝支付"); }
}
class WechatPay implements PayStrategy {
public void pay() { System.out.println("使用微信支付"); }
}
class PaymentContext {
private PayStrategy strategy;
public PaymentContext(PayStrategy strategy) {
this.strategy = strategy;
}
public void process() {
strategy.pay();
}
}
使用:
new PaymentContext(new Alipay()).process();
🌟 2. 模板方法模式(Template Method)—— 做菜一样写代码流程
场景:
- 统一业务流程步骤(如下单流程),但每步实现不同
- 多个子类共享流程框架
Java 示例:
abstract class OrderProcessor {
public final void process() {
selectProduct();
pay();
ship();
}
protected abstract void selectProduct();
protected abstract void pay();
protected abstract void ship();
}
class OnlineOrder extends OrderProcessor {
protected void selectProduct() { System.out.println("选择商品"); }
protected void pay() { System.out.println("在线支付"); }
protected void ship() { System.out.println("快递发货"); }
}
🌟 3. 观察者模式(Observer)—— 发布订阅的鼻祖
场景:
- 多模块监听某一事件(如用户下单后发短信、发邮件)
- 解耦通知者与监听者
Java 示例:
interface Observer {
void update(String msg);
}
class EmailNotifier implements Observer {
public void update(String msg) {
System.out.println("发送邮件:" + msg);
}
}
class OrderSubject {
private List<Observer> observers = new ArrayList<>();
public void addObserver(Observer o) {
observers.add(o);
}
public void notifyAll(String msg) {
for (Observer o : observers) {
o.update(msg);
}
}
}
🌟 4. 责任链模式(Chain of Responsibility)—— 一条龙处理流程
场景:
- 多个处理器按顺序处理请求(如审批流程、日志级别处理)
- 请求处理解耦
Java 示例:
abstract class Handler {
protected Handler next;
public void setNext(Handler h) { this.next = h; }
public abstract void handle(String msg);
}
class AuthHandler extends Handler {
public void handle(String msg) {
if (msg.contains("auth")) {
System.out.println("认证通过");
} else if (next != null) {
next.handle(msg);
}
}
}
使用:
Handler h1 = new AuthHandler();
Handler h2 = new LogHandler();
h1.setNext(h2);
h1.handle("auth+log");
🌟 5. 状态模式(State)—— 状态驱动行为变化
场景:
- 系统状态很多,状态驱动行为(如订单:待付款、已发货、已取消)
- 避免使用一堆 if/else
interface OrderState {
void handle();
}
class PaidState implements OrderState {
public void handle() {
System.out.println("订单已支付,准备发货");
}
}
class OrderContext {
private OrderState state;
public void setState(OrderState s) {
this.state = s;
}
public void process() {
state.handle();
}
}
🌟 6. 命令模式(Command)—— 把请求对象化,支持撤销/队列
场景:
- 需要记录操作、支持撤销
- 命令可能要延迟执行(任务队列)
interface Command {
void execute();
}
class SaveCommand implements Command {
public void execute() {
System.out.println("保存数据");
}
}
class Invoker {
private Command command;
public void setCommand(Command c) { this.command = c; }
public void invoke() { command.execute(); }
}
🌟 7. 解释器模式(Interpreter)—— 迷你语言解析器
场景:
- 实现 DSL(领域特定语言)
- 简单表达式解析器、规则引擎
interface Expression {
boolean interpret(String context);
}
class ContainsExpression implements Expression {
private String keyword;
public ContainsExpression(String keyword) {
this.keyword = keyword;
}
public boolean interpret(String context) {
return context.contains(keyword);
}
}
🌟 8. 备忘录模式(Memento)—— 悔棋专用
场景:
- 保存对象的历史状态,实现撤销/恢复功能(如编辑器)
class Editor {
private String content;
public void setContent(String c) { this.content = c; }
public String getContent() { return content; }
public Memento save() {
return new Memento(content);
}
public void restore(Memento m) {
content = m.getContent();
}
static class Memento {
private final String content;
public Memento(String c) { content = c; }
public String getContent() { return content; }
}
}
🌟 9. 中介者模式(Mediator)—— 群聊管理员
场景:
- 多个对象相互通信,关系混乱
- 想要统一协调通信关系
interface Mediator {
void notify(String msg, Colleague sender);
}
abstract class Colleague {
protected Mediator mediator;
public Colleague(Mediator m) { this.mediator = m; }
}
class ChatUser extends Colleague {
public void send(String msg) {
mediator.notify(msg, this);
}
public void receive(String msg) {
System.out.println("收到消息:" + msg);
}
}
🌟 10. 访问者模式(Visitor)—— 给不同对象统一加料
场景:
- 不改变对象结构,统一增加新操作
- 多类型节点统一访问(如 AST 遍历)
interface Element {
void accept(Visitor v);
}
class File implements Element {
public void accept(Visitor v) {
v.visit(this);
}
}
interface Visitor {
void visit(File f);
}
🌟 11. 迭代器模式(Iterator)—— 统一遍历方式
场景:
- 不暴露集合结构即可遍历集合
- 统一遍历不同数据结构
interface MyIterator<T> {
boolean hasNext();
T next();
}
✅ 三、总结速查表
| 模式 | 关键用途 | 解耦方式 |
|---|---|---|
| 策略 | 可切换算法 | 策略接口隔离 |
| 模板方法 | 固定流程 | 子类填空 |
| 观察者 | 事件通知 | 解耦通知者 |
| 责任链 | 顺序处理 | 解耦请求与处理者 |
| 状态 | 行为随状态变 | 状态封装行为 |
| 命令 | 请求对象化 | 请求与执行解耦 |
| 解释器 | 表达式计算 | 语法规则封装 |
| 备忘录 | 撤销恢复 | 状态封装 |
| 中介者 | 协调通信 | 统一调度 |
| 访问者 | 多类统一操作 | 操作独立抽出 |
| 迭代器 | 集合遍历 | 不暴露结构 |
📌 结语
“行为模式的核心不是‘行为’,而是让行为变得可控、可插拔、可扩展。”
——架构师不是把业务写清楚,是把变化处理好。
✅ 下一篇预告:
📖 第5篇|代码架构思维:解耦、分层、稳定性设计的那些套路
37

被折叠的 条评论
为什么被折叠?



