定義:爲子系統中的一組接口提供一個一致的界面。定義一個高層接口,使得這一子系統更加容易使用。
使用場景:子系統交互複雜,建立外觀模式可以屏蔽系統間的通信實現,客戶端調用簡單、透明。
結構:
外觀(Facade)角色:被客戶端調用,可以訪問各子系統的功能。
子系統(SubSystem)角色:實現子系統的功能,處理Facade指派的任務。
客戶端(Client)角色:調用外觀角色獲得相應的功能。
優點:
1、子系統間不必直接跟客戶端進行通信交互,減少耦合。
2、客戶端通過外觀角色直接跟子系統進行交互,對子系統間的通信是透明的。
這裏以電腦(簡單分爲cpu、內存、硬盤)爲例子,寫一個外觀模式的應用。
外觀角色類
public class Computer {
private Cpu cpu = null;
private Memory memory = null;
private HardDrive hardDrive = null;
public Computer(){
cpu = new Cpu();
memory = new Memory();
hardDrive = new HardDrive();
}
public void start(){
this.cpu.execute();
this.memory.execute();
this.hardDrive.execute();
}
}
子系統類
public class Cpu {
public void execute(){
System.out.println("CPU就緒!");
}
}
public class Memory {
public void execute(){
System.out.println("內存加載就緒!");
}
}
public class HardDrive {
public void execute(){
System.out.println("硬盤加載就緒!");
}
}
客戶端類
public class Client {
public static void main(String[] args){
Computer computer = new Computer();
computer.start();
}
}