外观模式:给复杂子系统开一扇门
下单接口要编排四件事:锁库存、扣款、加积分、发通知。Controller 注入四个 Service、自己操心调用顺序和事务边界——这是把「编排知识」复制到了每一个调用方,哪天积分逻辑挪了位置,所有编排点都要跟着改。外观模式(Facade)的定义:为复杂子系统提供一个统一的高层入口,编排细节封在门面里:
public class OrderFacade {
private final InventoryService inventoryService;
private final PaymentService paymentService;
private final PointService pointService;
private final NotifyService notifyService;
public OrderFacade(InventoryService inventoryService,
PaymentService paymentService,
PointService pointService,
NotifyService notifyService) {
this.inventoryService = inventoryService;
this.paymentService = paymentService;
this.pointService = pointService;
this.notifyService = notifyService;
}
// 调用方只看到一个方法,看不到子系统编排
public void placeOrder(Order order) {
inventoryService.lockStock(order);
paymentService.charge(order);
pointService.addPoints(order);
notifyService.sendSuccess(order);
}
}价值在依赖方向的收敛:外部只认门面,子系统内部重构(拆库、换实现、调整顺序)门面兜住,外部零感知。你天天在用的 SLF4J 连名字都写着——它是 Logback、Log4j2 的门面;Spring 的 ApplicationContext 也是个超级门面,把容器里成百个内部组件的能力汇总成 getBean、publishEvent 几个入口。注意与外观容易混的是中介者:外观是单向简化入口(外部调内部),中介者是双向协调枢纽(内部对象互相不认识,全靠它传话)。子系统只有两三个类时,门面纯属多余。
组合模式:叶子和容器一视同仁
内容管理系统的经典需求:分类里套子分类,子分类里还有文章,要统计任意节点下的文章总数。麻烦在于节点有两种身份——文章(叶子)和分类(容器),写统计逻辑得不停判断类型。组合模式(Composite)的答案:让叶子和容器实现同一个接口,调用方对两者一视同仁,容器内部递归委托:
// 统一接口:叶子与容器同构
public abstract class Node {
protected String name;
public Node(String name) {
this.name = name;
}
public abstract int count(); // 统计:叶子计 1,容器计全部
}
// 叶子:文章
public class Article extends Node {
public Article(String name) {
super(name);
}
@Override
public int count() {
return 1;
}
}
// 容器:分类,能装任何 Node(包括别的分类)
public class Category extends Node {
private final List<Node> children = new ArrayList<>();
public Category(String name) {
super(name);
}
public void add(Node node) {
children.add(node);
}
@Override
public int count() {
return children.stream().mapToInt(Node::count).sum(); // 递归
}
}统计「某个分类下所有文章」不再需要 if-else 判断类型——对 Node 统一调 count,容器自己递归。GUI 的组件树(容器装按钮)、Spring 的容器层级(父子 BeanFactory,子容器找不到就问父容器)、文件系统目录树,全是这个结构。识别标志:部分与整体需要被同样对待。反过来,层级固定两三层、结构不会生长的场景,直接两个字段更省事。
下一篇讲享元模式:一亿个对象长得都一样,为什么还在傻乎乎地 new?Integer 缓存的 == 陷阱也在那篇。
评论 (0)