美文网首页
10_外观模式

10_外观模式

作者: 真是个点子王 | 来源:发表于2021-01-13 14:54 被阅读0次
  • 外观模式又称为门面模式,是一种通过为多个复杂的子系统提供一个一致的接口,而使这些子系统更加容易被访问的模式。该模式对外有一个统一的接口,外部应用程序不用关系内部子系统的具体的细节,这样会大大降低应用程序的复杂程度,提高程序的可维护性。

结构

  • 外观(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("关闭家电");

    }
}

相关文章

网友评论

      本文标题:10_外观模式

      本文链接:https://www.haomeiwen.com/subject/miluaktx.html