外觀模式:為子系統中的一組接口提供一個一致的界面,此模式定義了一個高層接口,這個接口使得這一系統更加容易使用.
SubSystem Class 子系統類集合 實現子系統的功能,處理Facade對象指派的任務,注意子類中沒有Facade的任何信息,即沒有對Facade對象的引用
首先是四個子系統的類
public class SubSystemOne
{
public void MethodOne()
{
Console.WriteLine("子系統方法一");
}
}
public class SubSystemTwo
{
public void MethodTwo()
{
Console.WriteLine("子系統方法二");
}
}
public class SubSystemThree
{
public void MethodThree()
{
Console.WriteLine("子系統方法三");
}
}
public class SubSystemFour
{
public void MethodFour()
{
Console.WriteLine("子系統方法四");
}
}
外觀類
public 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("\n方法組A()----");
one.MethodOne();
two.MethodTwo();
four.MethodFour();
}
public void MethodB()
{
Console.WriteLine("\n方法組B()----");
two.MethodTwo();
three.MethodThree();
}
}
客戶端調用
class Program
{
static void Main(string[] args)
{
Facade facade = new Facade();
facade.MethodA();
facade.MethodB();
Console.ReadLine();
}
}
運行結果如下
首先,在設計初期階段,應該要有意識的將不同的兩個層分離。
其次,在開發階段,子系統往往因為不斷的重構演化而變得越來越復雜。增加外觀Facade可以提供一個簡單的接口,減少它們之間的依賴。
第三,在維護一個遺留的大型系統時,可能這個系統已經非常難以維護和擴展了。可以為新系統開發一個外觀Facade類,來提供設計粗糙或高度復雜的遺留代碼的比較清晰簡單的接口,讓新系統與Facade對象交互,Facade與遺留代碼交互所有復雜的工作。