外觀模式(Facade),爲子系統中的一組接口提供一個一致的界面,此模式定義了一個高層接口,這個接口使得這一子系統更加容易使用。
外觀模式完美的體現了依賴倒轉原則和迪米特法則的思想,所以是比較常見的設計模式之一。
外觀模式結構圖如下:
定義三個子系統類
public class SubSystemOne {
public void methodOne(){
System.out.println("子系統方法1");
}
}
public class SubSystemTwo {
public void methodTwo(){
System.out.println("子系統方法2");
}
}
public class SubSystemThree {
public void methodThree(){
System.out.println("子系統方法3");
}
}
定義一個外觀Facade類
public class Facade {
private SubSystemOne one;
private SubSystemTwo two;
private SubSystemThree three;
public Facade(){
one =new SubSystemOne();
two=new SubSystemTwo();
three=new SubSystemThree();
}
public void methodA(){
one.methodOne();
three.methodThree();
}
public void methodB(){
one.methodOne();
two.methodTwo();
}
}
客戶端代碼
public static void main(String[] args) {
Facade facade=new Facade();
facade.methodA();
facade.methodB();
}
由於Facade類的作用,客戶端可以根本不知道三個子系統的存在