意图

解决多个对象直接用起来比较复杂的问题

如何解决这个问题

通过一个高层对象来组合子系统的系统
Img

这样做的优势是什么

过去,客户端需要深入了解子系统的各种方法和类,耗费了大量精力。现在,有了这个门面类,客户端只需了解门面类的使用方式,大大降低了理解成本。

举个例子

设想一个家庭影院系统,包含DVD播放器、投影仪、灯光系统和音响设备。每个子系统都有独特的接口和方法。我们可以通过一个门面类来简化这些子系统的操作流程。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// 子系统类
class DVDPlayer {
public void on() { System.out.println("DVD Player on"); }
public void play(String movie) { System.out.println("Playing " + movie); }
public void off() { System.out.println("DVD Player off"); }
}

class Projector {
public void on() { System.out.println("Projector on"); }
public void setInput(String input) { System.out.println("Projector input set to " + input); }
public void off() { System.out.println("Projector off"); }
}

class Lights {
public void dim(int level) { System.out.println("Lights dimmed to " + level + "%"); }
public void on() { System.out.println("Lights on"); }
}

// 门面类
class HomeTheaterFacade {
private DVDPlayer dvd;
private Projector projector;
private Lights lights;

public HomeTheaterFacade(DVDPlayer dvd, Projector projector, Lights lights) {
this.dvd = dvd;
this.projector = projector;
this.lights = lights;
}

public void watchMovie(String movie) {
System.out.println("Get ready to watch a movie...");
lights.dim(10);
projector.on();
projector.setInput("DVD");
dvd.on();
dvd.play(movie);
}

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

// 客户端代码
public class Client {
public static void main(String[] args) {
DVDPlayer dvd = new DVDPlayer();
Projector projector = new Projector();
Lights lights = new Lights();

HomeTheaterFacade homeTheater = new HomeTheaterFacade(dvd, projector, lights);
homeTheater.watchMovie("Inception");
homeTheater.endMovie();
}
}

缺点

门面类抽象不完全:门面模式提供的接口可能无法覆盖子系统的所有功能,客户端可能仍需要直接调用子系统的某些方法。