A Sort Of A Blog
旧游无处不堪寻,无寻处,惟有少年心
设计模式-门面

门面模式(Facade Pattern)是一种结构型设计模式,能为程序库、框架或其他复杂类提供一个简单的接口。

门面模式 UML


适用场景


  1. 如果你需要一个指向复杂子系统的直接接口,且该接口的功能有限,则可以使用外观模式
  2. 如果需要将子系统组织为多层结构,可以使用外观

代码示例


using System;
namespace FacadePatternDemo
{
public class Facade
{
protected Subsystem1 _subsystem1;

protected Subsystem2 _subsystem2;

public Facade(Subsystem1 subsystem1, Subsystem2 subsystem2)
{
this._subsystem1 = subsystem1;
this._subsystem2 = subsystem2;
}

public string Operation()
{
string result = "Facade initializes subsystems:\n";
result += this._subsystem1.operation1();
result += this._subsystem2.operation1();
result += "Facade orders subsystems to perform the action:\n";
result += this._subsystem1.operationN();
result += this._subsystem2.operationZ();
return result;
}
}

public class Subsystem1
{
public string operation1()
{
return "Subsystem1: Ready!\n";
}

public string operationN()
{
return "Subsystem1: Go!\n";
}
}

public class Subsystem2
{
public string operation1()
{
return "Subsystem2: Get ready!\n";
}

public string operationZ()
{
return "Subsystem2: Fire!\n";
}
}

class Client
{
public static void ClientCode(Facade facade)
{
Console.Write(facade.Operation());
}
}

class Program
{
static void Main(string[] args)
{
Subsystem1 subsystem1 = new Subsystem1();
Subsystem2 subsystem2 = new Subsystem2();
Facade facade = new Facade(subsystem1, subsystem2);
Client.ClientCode(facade);
// output

// Facade initializes subsystems:
// Subsystem1: Ready!
// Subsystem2: Get ready!
// Facade orders subsystems to perform the action:
// Subsystem1: Go!
// Subsystem2: Fire!
}
}
}