解决问题
客户端调用逻辑与业务代码有效隔离,使得客户端调用只和Facade进行交互,内部的调用逻辑由Facade进行实现。此模式也可以和接口化编程结合,进一步降低客户端与业务逻辑的耦合
应用场景
它主要应用在代码结构的设计,合理组织代码结构
原理图(UML)
Facade 提供对客户端的接口和组织业务逻辑
示例
此模式非常常见,这里就直接使用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();
}
}