標籤:style blog http color os io 使用 ar art
返回目錄
在軟體系統中,某些類型由於自身的邏輯,它具有兩個或多個維度變化,那麼如何應對這種“多維度變化”?如何利用物件導向的技術來使得該類型能夠輕鬆的沿著多個方向進行變化,而又不引入額外的複雜度?這就要使用Bridge模式。
意圖
【GOF95】在提出橋樑模式的時候指出,橋樑模式的用意是"將抽象化(Abstraction)與實現化(Implementation)脫耦,使得二者可以獨立地變化"。這句話有三個關鍵詞,也就是抽象化、實現化和脫耦。
橋樑模式的成員
抽象化
存在於多個實體中的共同的概念性聯絡,就是抽象化。作為一個過程,抽象化就是忽略一些資訊,從而把不同的實體當做同樣的實體對待。
實現化
抽象化給出的具體實現,就是實現化,這裡的實現化不是具體的實現,而是一個介面或者抽象類別,它是對抽象化的擴充。
脫耦
所謂耦合,就是兩個實體的行為的某種強關聯。而將它們的強關聯去掉,就是耦合的解脫,或稱脫耦。在這裡,脫耦是指將抽象化和實現化之間的耦合解脫開,或者說是將它們之間的強關聯改換成弱關聯。將兩個角色之間的繼承關係改為彙總關係,就是將它們之間的強關聯改換成為弱關聯。因此,橋樑模式中的所謂脫耦,就是指在一個軟體系統的抽象化和實現化之間使用組合/彙總關係而不是繼承關係,從而使兩者可以相對獨立地變化。這就是橋樑模式的用意。何時能用到它?
某些類型由於自身的邏輯,它具有兩個或多個維度變化,這時使用橋樑模式
橋樑模式的結構圖
橋樑模式實現說明
Abstraction:抽象者,有對實現者的引用
RefinedAbstraction:更新抽象者,對抽象者進行擴充,它可以添加或者修改抽象者的部分功能
Implementor:實現者,它是一個介面或者功能類,它是對實現進行的一個抽象
ConcreteImplementorA:具體實現者,是實現Implementor的一種方式
橋樑模式的C#實現
#region bridge pattern #region 抽象者 // "Abstraction" class Abstraction { // Fields protected Implementor implementor; // Properties public Implementor Implementor { set { implementor = value; } } // Methods virtual public void Operation() { implementor.Operation(); } } // "RefinedAbstraction" class RefinedAbstraction : Abstraction { // Methods override public void Operation() { implementor.Operation(); } } #endregion #region 實現者 // "Implementor" abstract class Implementor { // Methods abstract public void Operation(); } // "ConcreteImplementorA" class ConcreteImplementorA : Implementor { // Methods override public void Operation() { Console.WriteLine("ConcreteImplementorA Operation"); } } // "ConcreteImplementorB" class ConcreteImplementorB : Implementor { // Methods override public void Operation() { Console.WriteLine("ConcreteImplementorB Operation"); } } #endregion #endregion
調用代碼
Abstraction abstraction = new RefinedAbstraction(); // Set implementation and call abstraction.Implementor = new ConcreteImplementorA(); abstraction.Operation(); // Change implemention and call abstraction.Implementor = new ConcreteImplementorB(); abstraction.Operation();
結果
返回目錄
說說設計模式~橋樑模式(Bridge)