首页 > 其他 > 详细

外观模式

时间:2019-03-01 17:40:45      阅读:169      评论:0      收藏:0      [点我收藏+]

1.基本概念

  • 定义一个高层同一的接口,Client通过这个统一的接口对子系统中的一群接口进行访问
  • 引入外观角色后,对象只需要与外观角色交互,不直接与子系统打交互,实现了客户端与子系统解耦
  • 使得子系统的使用更简单

  技术分享图片

2.代码

技术分享图片
package com.chengjie;

class SystemLight {
    public void on() {
        System.out.println("灯打开了!");
    }

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

class SystemTelevision {
    public void on() {
        System.out.println("电视打开了!");
    }

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

class SystemAircontion {
    public void on() {
        System.out.println("空调打开了!");
    }

    public void off() {
        System.out.println("空调关闭了!");
    }
}

class Facade {
    SystemLight sl;
    SystemTelevision st;
    SystemAircontion sa;

    public Facade(SystemLight sl, SystemTelevision st, SystemAircontion sa) {
        this.sl = sl;
        this.st = st;
        this.sa = sa;
    }

    public void on() {
        System.out.println("起床了!");
        this.sl.on();
        this.st.on();
        this.sa.on();
    }

    public void off() {
        System.out.println("睡觉了!");
        this.sl.off();
        this.st.off();
        this.sa.off();
    }
}

public class TestFacadePattern {
    public static void main(String[] args) {
        Facade f = new Facade(new SystemLight(), new SystemTelevision(), new SystemAircontion());
        f.on();
        f.off();
    }
}
View Code

3.优点

  • 实现客户类与子系统类的松耦合
  • 降低原有系统的复杂度,对客户屏蔽了子系统组件,从而简化了接口,
  • 提高了客户端使用的便捷性,使得客户端无须关心子系统的工作细节,通过外观角色即可调用相关功能。

4.缺点

  • 违背开闭原则:新增加子系统需要更改外观类代码

5.应用场景

  • 为一个复杂子系统提供简单的接口
  • 客户端与多个子系统有很大的依赖

6.参考

  https://www.jianshu.com/p/1b027d9fc005

外观模式

原文:https://www.cnblogs.com/forTheDream1991/p/10457505.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!