JavaRush /Java Blog /Random EN /Pattern (Template) of Delegation

Pattern (Template) of Delegation

Published in the Random EN group
Pattern (Template) of Delegation - let's look at the simplest example. There is a class Аwith some method f. A class Аis an internal, 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'll print to the console what the method does f. mainTo do this, create a class object in the method Аand call the method f. Now let's create the 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 Вcall the class method in the class method А.
class B{
   A a = new A();
   void f(){
      a.f();
   }
}
A class Вdelegates the execution of some tasks to another class. Вin this case class А.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION