深入理解Java設計模式之外觀模式
一、什么是外觀模式
定義:為子系統(tǒng)中的一組接口提供一個一致的界面,用來訪問子系統(tǒng)中的一群接口。

外觀模式組成:
Facade:負責子系統(tǒng)的的封裝調用
Subsystem Classes:具體的子系統(tǒng),實現(xiàn)由外觀模式Facade對象來調用的具體任務
二、外觀模式的使用場景
1、設計初期階段,應該有意識的將不同層分離,層與層之間建立外觀模式;
2、開發(fā)階段,子系統(tǒng)越來越復雜,增加外觀模式提供一個簡單的調用接口;
3、維護一個大型遺留系統(tǒng)的時候,可能這個系統(tǒng)已經(jīng)非常難以維護和擴展,但又包含非常重要的功能,為其開發(fā)一個外觀類,以便新系統(tǒng)與其交互。
三、外觀模式的優(yōu)缺點
優(yōu)點:
1、實現(xiàn)了子系統(tǒng)與客戶端之間的松耦合關系;
2、客戶端屏蔽了子系統(tǒng)組件,減少了客戶端所需處理的對象數(shù)目,并使得子系統(tǒng)使用起來更加容易。
缺點:
1、不符合開閉原則,如果要修改某一個子系統(tǒng)的功能,通常外觀類也要一起修改;
2、沒有辦法直接阻止外部不通過外觀類訪問子系統(tǒng)的功能,因為子系統(tǒng)類中的功能必須是公開的(根據(jù)需要決定是否使用internal訪問級別可解決這個缺點,但外觀類需要和子系統(tǒng)類在同一個程序集內)。
四、外觀模式的實現(xiàn)
先寫出四個子系統(tǒng)的類
class SubSystemOne
{
public void MethodOne()
{
Console.WriteLine("子系統(tǒng)方法一");
}
}
class SubSystemTwo
{
public void MethodTwo()
{
Console.WriteLine("子系統(tǒng)方法二");
}
}
class SubSystemThree
{
public void MethodThree()
{
Console.WriteLine("子系統(tǒng)方法三");
}
}
class SubSystemFour
{
public void MethodFour()
{
Console.WriteLine("子系統(tǒng)犯法四");
}
}
引入外觀類,減少子系統(tǒng)類之間的交互
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();
}
}
客戶端代碼:
static void Main(string[] args)
{
Facade facade = new Facade();
facade.MethodA();
facade.MethodB();
Console.Read();
}
總結
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關注腳本之家的更多內容!
相關文章
java基本教程之java線程等待與java喚醒線程 java多線程教程
這篇文章主要介紹了對線程等待/喚醒方法,文中使用了多個示例,大家參考使用吧2014-01-01
Netty分布式Future與Promise執(zhí)行回調相關邏輯剖析
這篇文章主要為大家介紹了Netty分布式Future與Promise執(zhí)行回調相關邏輯剖析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步2022-03-03
spring通過構造函數(shù)注入實現(xiàn)方法分析
這篇文章主要介紹了spring通過構造函數(shù)注入實現(xiàn)方法,結合實例形式分析了spring通過構造函數(shù)注入的原理、實現(xiàn)步驟及相關操作注意事項,需要的朋友可以參考下2019-10-10
spring boot下mybatis配置雙數(shù)據(jù)源的實例
這篇文章主要介紹了spring boot下mybatis配置雙數(shù)據(jù)源的實例,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-09-09

