外观模式
设计模式其实就是一种处理问题的方法,是一种思想,所以不能断言说只有多少种设计模式,因为思想是活跃的,一直在跳动,新的思想也在不断产生,外观模式也是经常使用的一种的设计模式;
定义:提供一个统一的接口去访问多个子系统的多个不同的接口,外观模式定义了一个高层次的接口,使得子系统更容易被使用。也就是说,设计一些独立的子系统,然后设计一个统一的接口去访问这些子系统,对他们进行组合,减少彼此间的耦合,提高代码的重用性。
UML图:

其中类和对象的关系为:
◆ Facade:外形类
● 知道哪些子系统负责处理哪些请求;
● 将客户的请求传递给相应的子系统对象处理。
◆ SubSystem:子系统类
● 实现子系统的功能;
● 处理Facade传递的任务;
● 子系统不知道Facade,在任何地方也没有应用Facade。
实例:
假定我们要设计一个冲茶系统,包括茶杯、水、茶包各类,我们创造一个Facade类来耦合各个类以完成操作;
定义子系统茶包TeaBag:
public class TeaBag {
public TeaBag() {
System.out.println("清香的茶包准备好了!");
}
}
定义子系统水Water:
public class Water {
boolean waterIsBoiling;
public Water() {
setWaterIsBoiling(false);
System.out.println("纯净的水准备好了!");
}
public void boilFacadeWater() {
setWaterIsBoiling(true);
System.out.println("水在沸腾!");
}
public void setWaterIsBoiling(boolean isWaterBoiling) {
waterIsBoiling = isWaterBoiling;
}
public boolean getWaterIsBoiling() {
return waterIsBoiling;
}
}
定义子系统茶杯:TeaCup
public class TeaCup {
boolean teaBagIsSteeped;
Water water;
TeaBag teaBag;
public TeaCup() {
setTeaBagIsSteeped(false);
System.out.println("茶杯准备好了!");
}
public void setTeaBagIsSteeped(boolean isTeaBagSteeped) {
teaBagIsSteeped = isTeaBagSteeped;
}
public boolean getTeaBagIsSteeped() {
return teaBagIsSteeped;
}
public void addTeaBag(TeaBag teaBag) {
this.teaBag = teaBag;
System.out.println("茶包放在杯子里了!");
}
public void addWater(Water water) {
this.water = water;
System.out.println("水倒入杯子里了!");
}
public void steepTeaBag() {
if ((teaBag != null)
&& ((water != null) && (water.getWaterIsBoiling()))) {
System.out.println("茶已经泡上了!");
setTeaBagIsSteeped(true);
} else {
System.out.println("茶没有泡");
setTeaBagIsSteeped(false);
}
}
public String toString() {
if (this.getTeaBagIsSteeped()) {
return ("一杯又香又浓的茶冲好了!");
} else {
return ("泡茶出了问题,请检查你的茶具!");
}
}
}
定义泡茶机器外观类:TeaMaker
public class TeaMaker {
boolean teaBagIsSteeped;
public TeaMaker() {
System.out.println("TeaMaker 准备为你泡茶了!");
}
public TeaCup makeACup() {
TeaCup cup = new TeaCup();
TeaBag teaBag = new TeaBag();
Water water = new Water();
cup.addTeaBag(teaBag);
water.boilFacadeWater();
cup.addWater(water);
cup.steepTeaBag();
return cup;
}
}
这样一整套的泡茶系统就设计好了,顾客只要泡茶就可以了:
public class Client{
public static void main(String[] args){
TeaMaker teaMaker=new TeaMaker();
TeaCup teaCup=teaMaker.makeACup();
System.out.println(teaCup);
}
},外观模式提供一个简单且公用的接口去处理复杂的子系统,并且没有减少子系统的功能,它遮蔽了子系统的复杂性,避免客户直接与子系统直接连接,也减少了子系统与子系统之间的连接,每个子系统都有它的Facade模式,每个子系统采用Facade模式去访问其他子系统,但是外观模式限制了客户的自由,减少了可变性,不过其灵活性还是可以的,各个系统间的耦合少!