结构型模式——外观模式
外观模式概述:
外观模式,又名门面模式,是一种通过为多个复杂的子系统提供一个一致的接口,而使这些子系统更加容易被访问的模式。该模式对外有一个统一的接口,外部应用程序不关心内部子系统的具体实现细节,这样会大大降低应用程序的复杂度,提高了程序的可用性。
外观模式结构:
外观模式包含一下角色:
- 外观角色:为多个子系统对外提供一个共同的接口。
- 子系统角色:实现系统的部分功能,客户可以通过外观角色访问它。
外观模式实现:
/**
* SmartApplication是外部角色
*/
public class SmartApplication {
private Light light;
private TV tv;
private AirCondition airCondition;
public SmartApplication(){
light = new Light();
tv = new TV();
airCondition = new AirCondition();
}
public void on(){
light.on();
tv.on();
airCondition.on();
}
public void off(){
light.off();
tv.off();
airCondition.off();
}
}
/**
* 以下都是内部角色
*/
public class AirCondition {
public void on(){
System.out.println("打开了空调");
}
public void off(){
System.out.println("关闭了空调");
}
}
public class Light {
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("关闭了电视");
}
}
外观模式优缺点:
- 好处:降低了子系统与客户端之间的耦合度,使得子系统的变化不会影响调用它的客户类。对客户屏蔽了子系统组件,减少了客户处理的对象数目,并使得子系统使用起来更加容易。
- 缺点:不符合开闭原则,修改很麻烦
文章内容为个人学习总结,如有错误望指正。
参考链接https://www.bilibili.com/video/BV1Np4y1z7BU