Delegation mode (Delegate)

Source: Internet
Author: User

The delegation mode (Delegate) is a common pattern in object-oriented design patterns. The principle of this pattern is that Class B and Class A are two classes that have no relation to each other, B has a method and a property that is exactly the same as a, and the method in B is called, and the property is called a method and a property of the same name in a. b seems to be an intermediary entrusted by a mandate. Third-party code does not need to know the existence of a, nor a direct contact with a, through B can directly use the function of a, so that both can use a variety of public energy, but also a good protection of a. Double benefit, wouldn't it be good. Here is a very simple example to explain the following:

Class a{
    void Method1 () {...}
    void Method2 () {...}
}
Class b{
    //delegation
    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
    }
    
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.