结构模式之外观模式

Posted by Night Field's Blog on March 29, 2020

1 概述

外观模式(Facade Pattern),也叫门面模式,是一种常见结构模式,它是面向对象设计封装思想的体现。

2 外观模式

所谓外观,其实是一个额外的类,它包含了复杂多变的子系统,并只对外提供简单的接口。相比于子系统,外观类提供的功能有限,因为它只包含外界真正关心的功能。 比如汽车只提供「方向盘」,「油门」,「刹车」几个简单元件供人使用,我们并不关心,也不需要关心发动机,刹车片是如何工作的。这里的汽车就是外观,而发动机刹车片,就是底层元件。 当实现某个功能需要多个模块集成在一起时,外观模式可以化繁为简,降低客户端(Client)与应用程序的耦合度。

3 案例

拿电脑举例子,我们按一下电脑的电源键,就可以启动电脑的各个部件。电脑其实就是一个外观类。

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
public class Test {
    public static void main(String[] args) {
        Computer facade = new Computer();
        // 使用外观类控制启动
        facade.startup();
        // 使用外观类控制关闭
        facade.shutdown();
    }
}

public class Computer {
    // 外观类持有模块对象
    ElectronicComponent motherboard = new Motherboard();
    ElectronicComponent cpu = new CPU();
    ElectronicComponent memory = new Memory();

    // 调用各个模块的相应方法
    public void startup() {
        motherboard.start();
        cpu.start();
        memory.start();
        System.out.println("Computer started!");
    }

    // 调用各个模块的相应方法
    public void shutdown() {
        motherboard.stop();
        cpu.stop();
        memory.stop();
        System.out.println("Computer has been shut down.");
    }
}

public interface ElectronicComponent {
    void start();
    void stop();
}

public class Motherboard implements ElectronicComponent {
    @Override
    public void start() { System.out.println("Motherboard is starting up"); }
    @Override
    public void stop() { System.out.println("Motherboard is shutting down..."); }
}

public class CPU implements ElectronicComponent {
    @Override
    public void start() { System.out.println("CPU is starting up..."); }
    @Override
    public void stop() { System.out.println("CPU is shutting down..."); }
}

public class Memory implements ElectronicComponent {
    @Override
    public void start() { System.out.println("Memory is starting up..."); }
    @Override
    public void stop() { System.out.println("Memory is shutting down..."); }
}

输出:

1
2
3
4
5
6
7
8
Motherboard is starting up
CPU is starting up...
Memory is starting up...
Computer started!
Motherboard is shutting down...
CPU is shutting down...
Memory is shutting down...
Computer has been shut down.

uml

外观对象电脑将复杂的一系列操作只封装为两个简单的方法startupshutdown,方便了客户端(调用者)的使用。同时客户端只需要依赖于外观对象,而不必与主板内存这些底层模块耦合,大大提高了代码的可维护性。

4 总结

当遇到多个不同的模块(接口)需要一起工作来完成某个功能时,可以考虑使用外观模式来降低系统复杂度。

文中例子的github地址