Facade 和 Template 方法模式有什么区别?它们都提供子系统的高级视图并将其对用户隐藏。
立面图案
internal class SubsystemA
{
internal string A1()
{
return "Subsystem A, Method A1\n";
}
internal string A2()
{
return "Subsystem A, Method A2\n";
}
}
internal class SubsystemB
{
internal string B1()
{
return "Subsystem B, Method B1\n";
}
}
internal class SubsystemC
{
internal string C1()
{
return "Subsystem C, Method C1\n";
}
}
public static class Facade
{
static SubsystemA a = new SubsystemA();
static SubsystemB b = new SubsystemB();
static SubsystemC c = new SubsystemC();
public static void Operation1()
{
Console.WriteLine("Operation 1\n" +
a.A1() +
a.A2() +
b.B1());
}
public static void Operation2()
{
Console.WriteLine("Operation 2\n" +
b.B1() +
c.C1());
}
}
// ============= Different compilation
// Compile with csc /r:FacadeLib.dll Facade-Main.cs
class Client
{
static void Main()
{
Facade.Operation1();
Facade.Operation2();
}
}
模板模式
interface IPrimitives
{
string Operation1();
string Operation2();
}
class Algorithm
{
public void TemplateMethod(IPrimitives a)
{
string s =
a.Operation1() +
a.Operation2();
Console.WriteLine(s);
}
}
class ClassA : IPrimitives
{
public string Operation1()
{
return "ClassA:Op1 ";
}
public string Operation2()
{
return "ClassA:Op2 ";
}
}
class ClassB : IPrimitives
{
public string Operation1()
{
return "ClassB:Op1 ";
}
public string Operation2()
{
return "ClassB.Op2 ";
}
}
class TemplateMethodPattern
{
static void Main()
{
Algorithm m = new Algorithm();
m.TemplateMethod(new ClassA());
m.TemplateMethod(new ClassB());
}
}
此示例取自O'Reilly 设计模式
在上面提供的示例中,外观和模板模式都实现了一个接口,并使用了一个抽象并定义了应该如何处理操作。我没有发现这两种模式之间有任何区别。谁能帮我理解一下。