C# 設計模式 之 橋接模式

來源:互聯網
上載者:User

       橋接模式關注如何設計抽象類別!
       主要目的是把一個抽象類別與其抽象操作的實現進行分離。
       抽象類別處於類階層的頂層位置,它定義了抽象的操作集,階層中的某些子類都為抽象操作集提供了不同的實現,這些操作集在一個介面中,另外還有子類沿著另外的方向,整個設計就是需要使用橋接模式。簡單的說,處於頂層位置的抽象類別的繼承出現多方向,需要使用橋接模式。

using System;
using System.Collections.Generic;
using System.Text;

namespace Bridge
...{
    /**//// <summary>
    /// 列印方式
    /// </summary>
    public abstract class PrintMethod
    ...{
        public abstract void Print();
    }

    /**//// <summary>
    /// 橫向方式
    /// </summary>
    public class Across : PrintMethod
    ...{
        public override void Print()
        ...{

            Console.WriteLine("--");
        }
    }

    /**//// <summary>
    /// 縱向方式
    /// </summary>
    public class Upright : PrintMethod
    ...{
        public override void Print()
        ...{
            Console.WriteLine("|");
        }
    }

    /**//// <summary>
    /// 機器
    /// </summary>
    public abstract class Machine
    ...{
        protected PrintMethod implementor;

        public PrintMethod Implementor
        ...{
            set ...{ implementor = value; }
        }

        public virtual void Print()
        ...{
            implementor.Print();
        }
    }

    /**//// <summary>
    /// 印表機
    /// </summary>
    public class Printer : Machine
    ...{
        public override void Print()
        ...{
            implementor.Print();
        }
    }

    /**//// <summary>
    /// 複印機
    /// </summary>
    public class Copycat : Machine
    ...{
        public override void Print()
        ...{
            implementor.Print();
        }
    }

    class Program
    ...{
        static void Main(string[] args)
        ...{
            Machine machine = new Printer();
            machine.Implementor = new Across();
            machine.Print();

            machine = new Copycat();
            machine.Implementor = new Upright();
            machine.Print();

            Console.ReadLine();
        }
    }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.