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
}
}