第十一章:外观模式
一、问题引入
现在我们开了个包子点,需要为我们的自动机器人设计一个程序来包包子。为完成目标我设计了一下两个类,实际情况下可能更多
这两个类中有很多相关的方法,我们需要调用里面的方法来进行包包子。通常我们在主类中 new 出这两个对象,然后根据流程调用相应的方法来完成业务。
然而这样会使主类中的存在太多的逻辑调用,是的项目难以维护,而且还和具体类产生耦合
二、外观模式
外观模式(Facade Pattern)提供了一个统一的接口,在外观类中我们将复杂的逻辑调用封装成几个简单的方法。
这样我们的主类就直接和这个门面类进行交互,避免了复杂的调用
具体实现:
Dough 类
public class Dough {
void dumpDough(int amount) {
System.out.println("倾倒" + amount + "的面粉");
}
void addWater(int amount) {
System.out.println("添加" + amount + "的水");
}
void kneadDough() {
System.out.println("正在和面中。。。");
}
}
Filling 类
public class Filling {
public void buyFilling(int amount) {
System.out.println("从市场上买了" + amount + "的馅");
}
public void chopFilling() {
System.out.println("正在将馅料剁成泥中。。。");
}
public void concocFilling() {
System.out.println("加入调味瓶,拌制馅料中。。。");
}
}
Facade 类
public class Facade {
private Dough dough;
private Filling filling;
public Facade() {
this.dough = new Dough();
this.filling = new Filling();
}
public void makeBun() {
dough.dumpDough(100);
dough.addWater(50);
dough.kneadDough();
filling.buyFilling(200);
filling.chopFilling();
filling.concocFilling();
}
}
测试类
public class FacadeTest {
public static void main(String[] args) {
Facade facade = new Facade();
facade.makeBun();
}
}
其实外观模式很简单,就是多做了一层封装而已
三、外观模式总结
1)外观模式对外屏蔽了子系统的细节,因此降低了调用者使用调用难度
2)外观模式将客户端与子系统解耦,让子系统内部的模块更易扩展
3)合理的使用外观模式,可以帮助我们更好的划分访问的层次
4)当维护一个遗留的大型系统时,可以考虑为难以扩展的老系统提供一个 Facade 类,来提供清晰简单的接口,让新系统和 Facade 类交互
5)不能无脑的使用外观模式,要以系统有层次,易扩展为目的