Pattern (Pattern) of Delegation - let's look at the simplest example. There is a class
А
with some method f
. A class А
is an inner non-static class of a class My
.
public class My{
public static void main(String[]args){
My test = new My();
My.A a1 = test.new A();
a1.f();
My.B b = test.new B();
b.f();
}
class A{
void f(){
System.out.println("f");
}
}
}
Then we print to the console what the method does f
. main
To do this, create a class object in the method А
and call the f
. Now let's create a class B
. We need it to do the same as the class А
, but we will not duplicate the code and we will not use inheritance either, but in the class В
we will create an object of the class А
, and then in the class method В
we will call the class method А
.
class B{
A a = new A();
void f(){
a.f();
}
}
A class В
delegates some tasks to another class. В
in this case the class А
.
GO TO FULL VERSION