解決問題
客戶端調(diào)用邏輯與業(yè)務代碼有效隔離喻鳄,使得客戶端調(diào)用只和Facade進行交互朦佩,內(nèi)部的調(diào)用邏輯由Facade進行實現(xiàn)开仰。此模式也可以和接口化編程結(jié)合蕊肥,進一步降低客戶端與業(yè)務邏輯的耦合
應用場景
它主要應用在代碼結(jié)構的設計,合理組織代碼結(jié)構
原理圖(UML)
Facade 提供對客戶端的接口和組織業(yè)務邏輯
示例
此模式非常常見扳埂,這里就直接使用wikipedia上的代碼
/* Complex parts */
class CPU {
public void freeze() { ... }
public void jump(long position) { ... }
public void execute() { ... }
}
class HardDrive {
public byte[] read(long lba, int size) { ... }
}
class Memory {
public void load(long position, byte[] data) { ... }
}
/* Facade */
class ComputerFacade {
private CPU processor;
private Memory ram;
private HardDrive hd;
public ComputerFacade() {
this.processor = new CPU();
this.ram = new Memory();
this.hd = new HardDrive();
}
public void start() {
processor.freeze();
ram.load(BOOT_ADDRESS, hd.read(BOOT_SECTOR, SECTOR_SIZE));
processor.jump(BOOT_ADDRESS);
processor.execute();
}
}
/* Client */
class You {
public static void main(String[] args) {
ComputerFacade computer = new ComputerFacade();
computer.start();
}
}