设计模式之外观模式

1. 定义

外部与一个子系统的通信必须通过一个统一的外观对象进行,为子系统中的一组接口提供一个一致的界面,外观模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。

2. 作用

为了实现客户类和子系统的解耦,降低系统的使用复杂度。比如说,我们晚上下班回家后,要打开电灯、空调、电视,如果能有个控制器,实现一键打开这些电器的功能就好了。

3. 结构

外观模式包含如下角色:

  • Facade: 外观角色
  • SubSystem:子系统角色

4. 实现

类图
  1. 子系统角色,就是上面提到的电灯、空调、电视,都可以被打开和关闭。
public class LightSystem {

    public void turnOn() {
        System.out.println("Turn on the light");
    }

    public void turnOff() {
        System.out.println("Turn off the light");
    }
}
public class TelevisionSystem {

    public void turnOn() {
        System.out.println("Turn on the tv");
    }

    public void turnOff() {
        System.out.println("Turn off the tv");
    }
}
public class AirConditionSystem {

    public void turnOn() {
        System.out.println("Turn on the air-condition");
    }

    public void turnOff() {
        System.out.println("Turn off the air-condition");
    }
}
  1. 外观角色,控制器,把各种电器的开闭都封装在这里,对外只提供一键操作的接口。
public class FacadeController {
    private LightSystem lightSystem;
    private TelevisionSystem televisionSystem;
    private AirConditionSystem airConditionSystm;

    public FacadeController() {
        lightSystem = new LightSystem();
        televisionSystem = new TelevisionSystem();
        airConditionSystm = new AirConditionSystem();
    }

    public void onKeyTurnOn() {
        lightSystem.turnOn();
        televisionSystem.turnOn();
        airConditionSystm.turnOn();
    }

    public void onKeyTurnOff() {
        lightSystem.turnOff();
        televisionSystem.turnOff();
        airConditionSystm.turnOff();
    }
}
  1. 客户类,使用控制器一键操作开关,省时又省力。
public class FacadeTest {

    public static void main(String[] args){
        System.out.println("-------- Turn on ----------");
        FacadeController facadeController = new FacadeController();
        facadeController.onKeyTurnOn();

        System.out.println("-------- Turn off ----------");
        facadeController.onKeyTurnOff();
    }
}

5. 优缺点

1. 优点:

对客户屏蔽子系统组件,减少了客户处理的对象数目并使得子系统使用起来更加容易。它实现了子系统与客户之间的松耦合关系,并降低了大型软件系统中的编译依赖性,简化了系统在不同平台之间的移植过程。

2. 缺点:

不能很好地限制客户使用子系统类,而且在不引入抽象外观类的情况下,增加新的子系统可能需要修改外观类或客户端的源代码,违背了「开闭原则」。

3. 使用场景:

要为一个复杂子系统提供一个简单接口;客户程序与多个子系统之间存在很大的依赖性;在层次化结构中,需要定义系统中每一层的入口,使得层与层之间不直接产生联系。

参考文章:

外观模式

外观模式

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容