概念介绍
外观模式(Facade),也叫“过程模式:外观模式为子系统中的一组接口提供 一个一致的界面,此模式定义了一个高层接口,这个接口使得这一子系统更加 容易使用
结构
-
外观(Facade)角色:为多个子系统对外提供一个共同的接口。
-
子系统(Sub System)角色:实现系统的部分功能,客户可以通过外观角色访问它。
-
客户(Client)角色:通过一个外观角色访问各个子系统的功能。
优劣势
优势
-
外观模式对外屏蔽了子系统的细节,因此外观模式降低了客户端对子系统使用的复 杂性
-
外观模式对客户端与子系统的耦合关系,让子系统内部的模块更易维护和扩展
-
降低了大型软件系统中的编译依赖性,简化了系统在不同平台之间的移植过程,因为编译一个子系统不会影响其他的子系统,也不会影响外观对象。
劣势
-
不能很好地限制客户使用子系统类。
-
增加新的子系统可能需要修改外观类或客户端的源代码,违背了“开闭原则”。
栗子
当我们下班回家 Codeing 的时候,我们打开门需要做的事情是,开电灯,开空调,开电脑等等,然后 Coding 完了之后又要 关电脑,关电灯。我们需要操作几个东西才能完成这一系列的动作,要是我们能用用一个开关来完成操作的话就好了。
类图
代码示例
/**
* @author yulecha
* @version 1.0.0
* @ClassName AirConditioner.java
* @Description 空调 (子系统角色 Sub System)
* @createTime 2019年11月18日 20:10:00
*/
public class AirConditioner {
private static AirConditioner airConditioner = new AirConditioner();
/**
* 饿汉式方式获取对象实例
* @return
*/
public static AirConditioner getInstance() {
return airConditioner;
}
public void on() {
System.out.println("开启开空调");
}
public void off() {
System.out.println("关闭空调");
}
}
/**
* @author yulecha
* @version 1.0.0
* @ClassName Light.java
* @Description 电灯 (子系统角色 Sub System)
* @createTime 2019年11月18日 20:32:00
*/
public class Light {
private static Light light = new Light();
public static Light getInstance() {
return light;
}
public void on() {
System.out.println("打开电灯");
}
public void off() {
System.out.println("关闭电灯");
}
}
/**
* @author yulecha
* @version 1.0.0
* @ClassName Computer.java
* @Description 电脑 (子系统角色 Sub System)
* @createTime 2019年11月18日 20:08:00
*/
public class Computer {
private static Computer computer = new Computer();
public static Computer getInstance() {
return computer;
}
public void on() {
System.out.println("打开电脑");
}
public void off() {
System.out.println("关闭电脑");
}
}
/**
* @author yulecha
* @version 1.0.0
* @ClassName CodingFacade.java
* @Description 外观 (外观角色 Facade)
* @createTime 2019年11月18日 20:07:00
*/
public class CodingFacade {
/**
* 定义各个子(系统)对象
*/
private Light light;
private AirConditioner airConditioner;
private Computer computer;
/**
* 一键开启电灯、空调、电脑
*/
public void on() {
light.on();
airConditioner.on();
computer.on();
}
/**
* 一键关闭电脑、电灯
*/
public void off() {
computer.off();
light.off();
}
public CodingFacade() {
this.light = Light.getInstance();
this.airConditioner = AirConditioner.getInstance();
this.computer = Computer.getInstance();
}
}
/**
* @author yulecha
* @version 1.0.0
* @ClassName Client.java
* @Description TODO
* @createTime 2019年11月19日 08:28:00
*/
public class Client {
public static void main(String[] args) {
CodingFacade codingFacade = new CodingFacade();
System.out.println("~~~~~~~~~回家~~~~~~~~~~~");
codingFacade.on();
System.out.println("~~~~~~~~~Coding结束~~~~~~~~~~~");
codingFacade.off();
}
}
~~~~~~~~~回家~~~~~~~~~~~
打开电灯
开启开空调
打开电脑
~~~~~~~~~Coding结束~~~~~~~~~~~
关闭电脑
关闭电灯
总结
外观模式挺好理解的,我这里的栗子虽然简单,但是你可以扩展着想,比如还要启动一些其他的东西。复杂点的话就是去一些地方办手续,要来来回回跑很多个地方才能办成,要是有个专门的部门负责这几个系统间的调用,那么我们直接和这个部门对接就行了,不用关心它要关联多少个部门。