委派模式(Delegate)

來源:互聯網
上載者:User

       委派模式(Delegate)是物件導向設計模式中常用的一種模式。這種模式的原理為類B和類A是兩個互相沒有任何關係的類,B具有和A一模一樣的方法和屬性;並且調用B中的方法,屬性就是調用A中同名的方法和屬性。B好像就是一個受A授權委託的中介。第三方的代碼不需要知道A的存在,也不需要和A發生直接的聯絡,通過B就可以直接使用A的功能,這樣既能夠使用到A的各種公能,又能夠很好的將A保護起來了。一舉兩得,豈不很好。下面用一個很簡單的例子來解釋下:

class A{    void method1(){...}    void method2(){...}}class B{    //delegation    A a = new A();   //method with the same name in A    void method1(){ a.method1();}    void method2(){ a.method2();}    //other methods and attributes    ...}public class Test{     public static void main(String args[]){    B b = new B();    b.method1();//invoke method2 of class A in fact    b.method2();//invoke method1 of class A in fact    }    }

聯繫我們

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