10_外观模式

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

结构

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

实例

  • 智能家居控制房屋内设备的开关。
public class Light {
    public void on(){
        System.out.println("打开电灯");
    }

    public void off(){
        System.out.println("关闭电灯");
    }
}

public class AirCondition {
    public void on(){
        System.out.println("打开空调");
    }
    public void off(){
        System.out.println("关闭空调");
    }
}

public class TV {
    public void on(){
        System.out.println("打开电视机");
    }
    public void off(){
        System.out.println("关闭电视机");
    }
}

public class SmartAppliancesFacade {

    private Light light;
    private TV tv;
    private AirCondition airCondition;

    public SmartAppliancesFacade() {
        light = new Light();
        tv = new TV();
        airCondition = new AirCondition();
    }

    // 通过语音控制
    public void say(String msg){
        if(msg.contains("打开")){
            on();
        }else if(msg.contains("关闭")){
            off();
        }else{
            System.out.println("我还听不懂你在说什么");
        }
    }

    // 一键打开功能
    private void on(){
        light.on();
        tv.on();
        airCondition.on();
    }

    // 一键关闭功能
    private void off(){
        light.off();
        tv.off();
        airCondition.off();
    }
}

public class Client {
    public static void main(String[] args) {
        SmartAppliancesFacade facade = new SmartAppliancesFacade();

        facade.say("打开家电");

        System.out.println("=======================");

        facade.say("关闭家电");

    }
}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容