說(shuo)說(shuo)設計模(mo)式~橋梁模(mo)式(Bridge)
在軟件系統中,某些類型由(you)于自身的(de)邏(luo)輯,它具有兩(liang)個或多(duo)個維(wei)(wei)度的(de)變(bian)化,那么(me)如(ru)何應(ying)對這種“多(duo)維(wei)(wei)度的(de)變(bian)化”?如(ru)何利(li)用面向對象的(de)技(ji)術來使(shi)得該類型能夠輕(qing)松的(de)沿著多(duo)個方向進行變(bian)化,而又不引入(ru)額(e)外的(de)復雜度?這就要使(shi)用Bridge模式。
意圖
【GOF95】在提出(chu)橋(qiao)梁模式的(de)時候指出(chu),橋(qiao)梁模式的(de)用意(yi)是"將(jiang)抽象化(hua)(Abstraction)與(yu)實現化(hua)(Implementation)脫(tuo)耦(ou),使得(de)二者可(ke)以獨立(li)地變化(hua)"。這句話有三個(ge)關鍵(jian)詞,也就是抽象化(hua)、實現化(hua)和脫(tuo)耦(ou)。
橋梁模式的成員
抽象化
實(shi)現化
脫耦
何時能用到它?
某些類型由于自身(shen)的邏(luo)輯,它(ta)具有兩(liang)個(ge)(ge)或(huo)多個(ge)(ge)維(wei)度的變化,這時使用橋梁模(mo)式(shi)
橋梁模式的結構圖
橋梁模式實現說明
Abstraction:抽(chou)象者,有對實現(xian)者的引用
RefinedAbstraction:更新(xin)抽象(xiang)者,對抽象(xiang)者進行擴展(zhan),它可以添加或(huo)者修(xiu)改抽象(xiang)者的部分(fen)功(gong)能
Implementor:實(shi)現者,它是一(yi)個(ge)接口或者功能類(lei),它是對實(shi)現進行(xing)的一(yi)個(ge)抽象(xiang)
ConcreteImplementorA:具體實現者,是實現Implementor的(de)一種方式
橋梁模式的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();
結果截圖