Search code examples
oopdelegation

Regarding delegation


When a class 'delegates' a task to another class:

Does the 'delegator' class have to pass itself to the 'delegated' class for it to count as delegation? Or is simple 'forwarding of responsibility' enough, without a class passing itself as a parameter?


Solution

  • No, it does not have to pass itself to the delegate. In fact, delegation is sometimes used in large classes to abstract away specific functions without passing.

    For example, if I have a bakery class, and I want to do bakery.sellALoafOfBread(), from the outside, it may just look like the bakery class took care of it. In reality, the cashier class, delegated to by the bakery, did the task. It returned the amount of money that a loaf of bread costs, and the bakery class added the money to the monthly profit.

    However, a large object may want to pass a pointer or a reference to itself if the delegate is really tied up in the large class. This way, the small class can have access to the large class's variables and other members.

    Example from Wikipedia:

     class RealPrinter { // the "delegate"
         void print() { 
           System.out.println("something"); 
         }
     }
    
     class Printer { // the "delegator"
         RealPrinter p = new RealPrinter(); // create the delegate 
         void print() { 
           p.print(); // delegation
         } 
     }
    
     public class Main {
         // to the outside world it looks like Printer actually prints.
         public static void main(String[] args) {
             Printer printer = new Printer();
             printer.print();
         }
     }
    

    See, no passing!