1. 简介
模拟一个需求:
前端需要生成一张报表,但是报表的数据来源于不同的模块,且来自不同的十几个接口的数据,如果让前端来做,意味着前端需要调用十几个接口,然后组装数据,前端估计mmp了,此时,如果后端提供那么一个接口,包含了所有需要的数据,那么对于后端来说,就可以使用外观模式了,简单的说,就是在一个接口里面,分别调用来自其他模块的api或者其他接口的数据,组装,返回给前端,如此下来,对于前端而言就只需要调用一个接口即可;
2. 代码演示
2.1 外观类内部的子系统
package facade.subsystem;
public class SubSystemOne {
public void methodOne() {
System.out.println("子系统方法一");
}
}
package facade.subsystem;
public class SubSystemTwo {
public void methodTwo() {
System.out.println("子系统方法二");
}
}
package facade.subsystem;
public class SubSystemThree {
public void methodThree() {
System.out.println("子系统方法三");
}
}
package facade.subsystem;
public class SubSystemFour {
public void methodFour() {
System.out.println("子系统方法四");
}
}
2.2 外观类
package facade;
import facade.subsystem.SubSystemFour;
import facade.subsystem.SubSystemOne;
import facade.subsystem.SubSystemThree;
import facade.subsystem.SubSystemTwo;
public class Facade {
SubSystemOne one;
SubSystemTwo two;
SubSystemThree three;
SubSystemFour four;
public Facade() {
this.one = new SubSystemOne();
this.two = new SubSystemTwo();
this.three = new SubSystemThree();
this.four = new SubSystemFour();
}
public void MethodA() {
System.out.println("方法组A()----");
one.methodOne();
two.methodTwo();
four.methodFour();
}
public void MethodB() {
System.out.println("方法组B()----");
two.methodTwo();
three.methodThree();
}
}
3. 测试类
package facade;
/**
* 外观/门面模式
*/
public class FacadePattern {
public static void main(String[] args) {
Facade facade = new Facade();
facade.MethodA();
facade.MethodB();
System.out.println("----over----");
}
}