外观模式的UML类图
外观模式的应用场景
在以下情况下可以考虑使用外观模式:
(1)设计初期阶段,应该有意识的将不同层分离,层与层之间建立外观模式。
(2) 开发阶段,子系统越来越复杂,增加外观模式提供一个简单的调用接口。
(3) 维护一个大型遗留系统的时候,可能这个系统已经非常难以维护和扩展,但又包含非常重要的功能,为其开发一个外观类,以便新系统与其交互。
外观模式的实现
1、各个子模块
public class SubSystemOne {
public void methodOne(){
System.out.println("methodOne");
}
}
public class SubSystemTwo {
public void methodTwo(){
System.out.println("methodTwo");
}
}
public class SubSystemThree {
public void methodThree(){
System.out.println("methodThree");
}
}
public class SubSystemFour {
public void methodFour(){
System.out.println("methodFour");
}
}
2、外观者,将各个子模块集成
public class Facade {
//将所有模块进行集成
SubSystemOne systemOne;
SubSystemTwo systemTwo;
SubSystemThree systemThree;
SubSystemFour systemFour;
public Facade(){
systemOne = new SubSystemOne();
systemTwo = new SubSystemTwo();
systemThree = new SubSystemThree();
systemFour = new SubSystemFour();
}
public void methodA(){
systemOne.methodOne();
systemTwo.methodTwo();
systemThree.methodThree();
}
public void methodB(){
systemFour.methodFour();
}
}
3、客户端
public class Client {
public static void main(String[] args) {
//客户端和其他模块不耦合,只与Facade耦合
Facade facade = new Facade();
facade.methodA();
facade.methodB();
}
}