一.定义
外观模式(Facade Pattern):外部与一个子系统的通信必须通过一个统一的外观对象进行,为子系统中的一组接口提供一个一致的界面,外观模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。外观模式又称为门面模式,它是一种对象结构型模式。
二、模式结构成员构成
• Facade: 外观角色
• SubSystem:子系统角色
三.代码示例
View Code
1 /** 2 * SubSystem 3 * 内部子系统角色 4 */ 5 public class CPU { 6 public void freeze() { 7 } 8 9 public void jump(long position) { 10 } 11 12 public void execute() { 13 } 14 } 15 16 /** 17 * SubSystem 18 * 内部子系统 19 */ 20 public class Memory { 21 public void load(long position, byte[] data) { 22 23 } 24 } 25 26 /** 27 * SubSystem 28 * 内部子系统角色 29 */ 30 public class HardDrive { 31 public byte[] read(long lba, int size) { 32 return null; 33 } 34 } 35 36 /** 37 * Facade 38 * 外观角色角色 39 */ 40 public class Computer { 41 42 //统一管理内部子系统 43 private CPU cpu = new CPU(); 44 private HardDrive hardDrive = new HardDrive(); 45 private Memory memory = new Memory(); 46 47 long BOOT_ADDRESS; 48 long BOOT_SECTOR; 49 int SECTOR_SIZE; 50 51 public void startComputer() { 52 cpu.freeze(); 53 memory.load(BOOT_ADDRESS, hardDrive.read(BOOT_SECTOR, SECTOR_SIZE)); 54 cpu.jump(BOOT_ADDRESS); 55 cpu.execute(); 56 } 57 } 58 59 /** 60 * client 61 */ 62 public class Client { 63 public static void main(String[] args) { 64 Computer facade = new Computer(); 65 facade.startComputer(); 66 } 67 }