外观模式


请输入要查询的词条内容:

外观模式


外观模式是软件工程中常用的一种软件设计模式。它为子系统中的一组接口提供一个统一的高层接口。使用子系统更容易使用。

结构

Facade

这个外观类为子系统中Packages 1、2、3提供一个共同的对外接口

Clients

客户对象通过一个外观接口读写子系统中各接口的数据资源。

Packages

客户可以通过外观接口读取的内部库。

示例

Java

这是一个抽象的示例。一个客户“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();

}

}

C#

// 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("\MethodA() ---- ");

one.MethodOne();

two.MethodTwo();

four.MethodFour();

}

public void MethodB()

{

Console.WriteLine("\MethodB() ---- ");

two.MethodTwo();

three.MethodThree();

}

}

}

相关分词: 外观 模式