外观模式(Facade Pattern)

提供了一个统一的接口,用来访问子系统中的一群接口,外观定义了一个高层的接口,让子系统更容易使用。其实就是为了方便客户的使用,把一群操作,封装成一个方法

外观模式,就是“method”层面上的组合模式,上个章节的组合模式是多个类,而外观模式就是多个方法。

场景描述

你有一个家庭影院系统,包含以下设备:

  • 影碟机(DVD Player)
  • 投影仪(Projector)
  • 音响(Sound System)
  • 灯光(Lights)

每次想要看电影时,你需要手动做以下操作:

  1. 关灯
  2. 打开投影仪
  3. 启动音响
  4. 播放DVD

看完电影后又要一次关闭这些设备。

这个过程非常繁琐,而外观模式可以封装这些复杂逻辑,对外提供一个简单接口,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class HomeTheaterFacade {
...
public void watchMovie(String movie) {
System.out.println("Get ready to watch a movie...");
lights.dim(10);
projector.on();
projector.setInput(dvdPlayer);
amplifier.on();
amplifier.setVolume(75);
amplifier.setInput(dvdPlayer);
dvdPlayer.on();
dvdPlayer.play(movie);
}

public void endMovie() {
System.out.println("Shutting movie theater down...");
dvdPlayer.stop();
dvdPlayer.off();
amplifier.off();
projector.off();
lights.off();
}
}

我只需要“一键”观影即可。

总结

优点

  • 简化接口,不需要了解每个子系统的细节
  • 解耦,客户端只依赖外观类,不与具体子系统耦合
  • 提高维护性,子系统的变化,只需要修改外观类,不影响客户端

其它常见应用示例

  1. 编译器/解析器,将词法分析、语法分析、语义分析处理封装成一个Compiler外观
  2. 支付系统中对接多个支付渠道(微信、支付宝、银联),统一调用接口