「设计模式」外观模式

69 阅读2分钟

一、概述

外观模式(Facade Pattern)隐藏系统的复杂性,并向客户端提供了一个客户端可以访问系统的接口。这样接口调用方和接口提供方提供了一个中间层,用于包装逻辑提供API接口。

个人理解,就是提供一个客户端可以直接调用的二次封装的接口层

外观模式的2种角色:

外观(Facade)角色:为多个子系统对外提供一个共同的接口。

子系统(Sub System)角色:实现系统的部分功能,客户可以通过外观角色访问它。

二、优缺点

优点: 1、减少系统相互依赖。 2、提高灵活性。 3、提高了安全性。

**缺点:**不符合开闭原则,如果要改东西很麻烦,继承重写都不合适。

三、实现方式

外观模式在所有设计模式中,算是比较简单的设计模式,下面简单实现外观设计模式。

在关机的时候,需要分别关闭显示屏、关闭音响、关闭主机等设备,现开发了一个设备,直接关机设备,可以关闭所有设备或关闭其中某个设备。

子系统类

public class StopHost {
    public void execute(){
        System.out.println("关闭主机设备");
    }
}

public class StopMonitor {
    public void execute(){
        System.out.println("关闭显示屏设备");
    }
}

public class StopSound {
    public void execute(){
        System.out.println("关闭音响设备");
    }
}

外观类

public class StopEquipment {

    StopMonitor stopMonitor;
    StopSound stopSound;
    StopHost stopHost;

    public StopEquipment(){
        this.stopHost = new StopHost();
        this.stopMonitor = new StopMonitor();
        this.stopSound = new StopSound();
    }

    public void executeStopAll(){
        stopSound.execute();
        stopMonitor.execute();
        stopHost.execute();
        System.out.println("已关闭所有设备");
    }

    public void executeStopSound(){
        stopSound.execute();
        System.out.println("仅关闭了音响设备");
    }
    
}

客户端

public class Client {
    public static void main(String[] args) {
        StopEquipment stopEquipment = new StopEquipment();
        System.out.println("执行关闭所有设备接口");
        stopEquipment.executeStopAll();
        System.out.println("----------------");
        System.out.println("执行关闭音响接口");
        stopEquipment.executeStopSound();
    }
}

结果输出

执行关闭所有设备接口
关闭音响设备
关闭显示屏设备
关闭主机设备
已关闭所有设备
----------------
执行关闭音响接口
关闭音响设备
仅关闭了音响设备

四、常见应用场景

  • 对分层结构系统构建时,使用外观模式定义子系统中每层的入口点可以简化子系统之间的依赖关系。
  • 当一个复杂系统的子系统很多时,外观模式可以为系统设计一个简单的接口供外界访问。
  • 当客户端与多个子系统之间存在很大的联系时,引入外观模式可将它们分离,从而提高子系统的独立性和可移植性。