設計模式學習筆記六——Adapter模式

來源:互聯網
上載者:User
動機:將一個類的介面轉換成客戶希望的另外一個介面,使得原本由於介面不相容而不能一起工作的那些類可以一起工作。

應用:舊代碼複用、類庫遷移等。

情境:原有一隻SP/2介面的滑鼠,現想插在ThinkPad T60上使用,由於T60滑鼠介面為USB介面,所以需要一個轉換器進行轉接。

說明:適配器包括兩種實現結構:對象適配器和類適配器。類適配器使用多繼承,帶來不良的高耦合,一般不使用。

結構

代碼實現

namespace DesignPattern.Adapter
{

    /**//// <summary>
    /// 原有類
    /// </summary>
    public class SP2Mouse
    {
        public void MoveSP2()
        {
        }

        public void TuneSP2()
        {
        }
    }

    /**//// <summary>
    /// 客戶希望的介面
    /// </summary>
    interface IMouse
    {
        void Init();
        void Move();
        void Tune();
        void End();
    }

   /**//// <summary>
   /// 對象適配器
   /// </summary>
    public class MouseAdapter : IMouse
    {
        SP2Mouse sp2Mouse;  // 被適配對象

        public MouseAdapter()
        {
            sp2Mouse = new SP2Mouse();
        }

        public void Init()
        {
        }

        public void Move()
        {
            sp2Mouse.MoveSP2();
            
            // Do something else
        }

        public void Tune()
        {
            sp2Mouse.TuneSP2();

            // Do something else
        }

        public void End()
        {
        }
    }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.