外观(Facade)模式,又叫做门面模式,它为一组接口提供了一个一致界面。外观模式定义了一个高层接口,这个接口使这一组接口更加容易使用
日常使用Spring开发中,在高层模块需要使用多个子系统,我们都会创建一个新的类封装这些子系统,对外提供,这其实也是外观模式的一种体现。
外观模式是“迪米特法则”的典型应用,有如下优点:
- 降低子系统和客户端的耦合度
- 简化了使用过程
缺点:
- 增加新的子系统就需要修改代码,违背了开闭原则
结构实现:
外观模式结构比较简单,主要是定义了一个高层接口,包含了对各个子系统的引用
- 外观角色:高层接口,对外提供服务,内部引用多个子子系统
- 子系统:实现整个系统的部分功能,客户端可以通过外观角色访问
- 客户端:调用方,通过外观访问不同的子角色
示例:
现在有一些积木玩具,这些积木都被放在一个盒子里面,现在我们需要从盒子里面取出方形的积木。
public static void main(String[] args) {
Facade facade = new FacadeImpl();
System.out.println(facade.getSquare());//方形积木
}
// 外观--提供操作
interface Facade{
// 获取方形
String getSquare();
// 获取圆形
String getCircle();
}
// 实现外观操作
static class FacadeImpl implements Facade{
Square square = new Square();
Circle circle = new Circle();
@Override
public String getSquare() {
return square.toString();
}
@Override
public String getCircle() {
return circle.toString();
}
}
// 子系统1
static class Square{
@Override
public String toString() {
return "方形积木";
}
}
// 子系统2
static class Circle{
@Override
public String toString() {
return "圆形积木";
}
}