1. 程式人生 > 其它 >橋接模式——1.分類2.找聯絡3.繼承

橋接模式——1.分類2.找聯絡3.繼承

技術標籤:設計模式

  橋接模式(Bridge)定義:將抽象部分與它的顯示部分分離,使它們都可以獨立地變化。
  橋接模式的目的是鬆耦合,另外也用到了合成/聚合複用原則(儘量使用合成/聚合,儘量不要使用繼承)。因為繼承是一種強耦合關係,所以我們優先考慮把類分好,然後找到類之間的合成/聚合關係,到最後再使用繼承。

Implementor類:

    abstract  class Implementor
    {
        public abstract void Operation();//抽象方法Operation()
    }

子類:

    class ConcreteImplementorA
:Implementor { public override void Operation()//重寫 { Console.WriteLine("具體實現A的方法執行"); } } class ConcreteImplementorB : Implementor { public override void Operation()//重寫 { Console.WriteLine("具體實現B的方法執行"
); } }

Abstraction類:

    class Abstraction
    {
        protected Implementor implementor;//例項化父類
        public void SetImplementor(Implementor  implementor)//Implementor類作為Abstraction類的方法引數
        {
            this.implementor = implementor;
        }
        public virtual void Operation
()//虛方法 { implementor.Operation(); } }

RefinedAbstraction類

    class RefinedAbstraction:Abstraction
    {
        public override void Operation()//重寫
        {
            implementor .Operation();
        }
    }

客戶端:

        static void Main(string[] args)
        {
            Abstraction ab = new RefinedAbstraction();//父類的實現指向子類的例項
            //例項化ConcreteImplementorA類的物件,通過方法SetImplementor()把值給Implementor類例項化的物件implementor
            ab.SetImplementor(new ConcreteImplementorA ());//這裡也是裡式轉換
            ab.Operation();//執行Implementor類的物件implementor的方法Operation(),實際是執行ConcreteImplementorA類的方法Operation(),顯示“實現具體的方法A”

            ab.SetImplementor(new ConcreteImplementorB());//同樣操作
            ab.Operation();

            Console.Read();
        }
    }