外观模式又叫作门面模式,是一种通过为多个复杂的子系统提供一个一致的接口,而使这些子系统更加容易被访问的模式。
该模式对外有一个统一接口,外部应用程序不用关心内部子系统的具体细节,这样会大大降低应用程序的复杂度,提高了程序的可维护性。

优点】

  • 降低了子系统与客户端之间的耦合度,使得子系统的变化不会影响调用它的客户类。
  • 对客户屏蔽了子系统组件,减少了客户处理的对象数目,并使得子系统使用起来更加容易。
  • 降低了大型软件系统中的编译依赖性,简化了系统在不同平台之间的移植过程,因为编译一个子系统不会影响其他的子系统,也不会影响外观对象。


【缺点】

  • 不能很好地限制客户使用子系统类,很容易带来未知风险。
  • 增加新的子系统可能需要修改外观类或客户端的源代码,违背了“开闭原则”。

【角色】

  • 外观角色(Facade):为多个子系统对外提供一个共同的接口。
  • 子系统角色(Sub System):实现系统的部分功能,客户可以通过外观角色访问它。
  • 客户角色(Client):通过一个外观角色访问各个子系统的功能。

    1. /**
    2. * 空调
    3. */
    4. public class AirCondition {
    5. public void on() {
    6. System.out.println("空调打开...");
    7. }
    8. public void off() {
    9. System.out.println("空调关闭...");
    10. }
    11. }
    1. /**
    2. * 灯光
    3. */
    4. public class Light {
    5. public void on() {
    6. System.out.println("灯光打开...");
    7. }
    8. public void off() {
    9. System.out.println("灯光关闭...");
    10. }
    11. }
    1. /**
    2. * 电视
    3. */
    4. public class TV {
    5. public void on() {
    6. System.out.println("电视打开...");
    7. }
    8. public void off() {
    9. System.out.println("电视关闭...");
    10. }
    11. }
    1. /**
    2. * 智能控制器
    3. */
    4. public class SmartController {
    5. private AirCondition airCondition;
    6. private Light light;
    7. private TV tv;
    8. public SmartController() {
    9. airCondition = new AirCondition();
    10. light = new Light();
    11. tv = new TV();
    12. }
    13. public void open() {
    14. System.out.println("## 一键开启 ##");
    15. airCondition.on();
    16. light.on();
    17. tv.on();
    18. }
    19. public void close() {
    20. System.out.println("## 一键关闭 ##");
    21. airCondition.off();
    22. light.off();
    23. tv.off();
    24. }
    25. }

    ```java public class FacadeTest { public static void main(String[] args) {

    1. SmartController smartController = new SmartController();
    2. smartController.open();
    3. System.out.println();
    4. smartController.close();

    } } ——输出——

    一键开启

    空调打开… 灯光打开… 电视打开…

一键关闭

空调关闭… 灯光关闭… 电视关闭… ```