JavaRush /Java Blog /Random EN /Pattern (Pattern) Delegations

Pattern (Pattern) Delegations

Published in the Random EN group
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. mainTo 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 А.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION