外观模式
2019-03-01 17:06 剑动情缥缈 阅读(188) 评论(0) 编辑 收藏 举报1.基本概念
- 定义一个高层同一的接口,Client通过这个统一的接口对子系统中的一群接口进行访问
- 引入外观角色后,对象只需要与外观角色交互,不直接与子系统打交互,实现了客户端与子系统解耦
- 使得子系统的使用更简单
2.代码
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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(); } }
3.优点
- 实现客户类与子系统类的松耦合
- 降低原有系统的复杂度,对客户屏蔽了子系统组件,从而简化了接口,
- 提高了客户端使用的便捷性,使得客户端无须关心子系统的工作细节,通过外观角色即可调用相关功能。
4.缺点
- 违背开闭原则:新增加子系统需要更改外观类代码
5.应用场景
- 为一个复杂子系统提供简单的接口
- 客户端与多个子系统有很大的依赖
6.参考
https://www.jianshu.com/p/1b027d9fc005