外观模式(Facade pattern),是软件工程中常用的一种软件设计模式,它为子系统中的一组接口提供一个统一的高层接口,使得子系统更容易使用。
这是一个抽象的示例。一个客户“you”通过外观接口“computer”获取计算机内部复杂的系统信息。
/* Complex parts */class CPU { public void freeze() { ... } public void jump(long position) { ... } public void execute() { ... }}class Memory { public void load(long position, byte data) { ... }}class HardDrive { public byte read(long lba, int size) { ... }}/* Façade */class Computer { public void startComputer() { cpu.freeze(); memory.load(BOOT_ADDRESS, hardDrive.read(BOOT_SECTOR, SECTOR_SIZE)); cpu.jump(BOOT_ADDRESS); cpu.execute(); }}/* Client */class You { public static void main(String args) { Computer facade = new Computer(); facade.startComputer(); }}
// Facade pattern -- Structural example using System;namespace DoFactory.GangOfFour.Facade.Structural{ // Mainapp test application class MainApp { public static void Main() { Facade facade = new Facade(); facade.MethodA(); facade.MethodB(); // Wait for user Console.Read(); } } // "Subsystem ClassA" class SubSystemOne { public void MethodOne() { Console.WriteLine(" SubSystemOne Method"); } } // Subsystem ClassB" class SubSystemTwo { public void MethodTwo() { Console.WriteLine(" SubSystemTwo Method"); } } // Subsystem ClassC" class SubSystemThree { public void MethodThree() { Console.WriteLine(" SubSystemThree Method"); } } // Subsystem ClassD" class SubSystemFour { public void MethodFour() { Console.WriteLine(" SubSystemFour Method"); } } // "Facade" class Facade { SubSystemOne one; SubSystemTwo two; SubSystemThree three; SubSystemFour four; public Facade() { one = new SubSystemOne(); two = new SubSystemTwo(); three = new SubSystemThree(); four = new SubSystemFour(); } public void MethodA() { Console.WriteLine("\nMethodA() ---- "); one.MethodOne(); two.MethodTwo(); four.MethodFour(); } public void MethodB() { Console.WriteLine("\nMethodB() ---- "); two.MethodTwo(); three.MethodThree(); } }}
class CPU {public: void freeze() { ... } void jump(long position) { ... } void execute() { ... }}class Memory {public: void load(long position, char* data) { ... }}class HardDrive {public: char* read(long lba, int size) { ... }}/* Façade */class Computer {public: void startComputer() { cpu.freeze(); memory.load(BOOT_ADDRESS, hardDrive.read(BOOT_SECTOR, SECTOR_SIZE)); cpu.jump(BOOT_ADDRESS); cpu.execute(); }}/* Client */class You {public: void start(String args) { Computer facade = new Computer(); facade.startComputer(); }}