less than 1 minute read

use delegation when you need an object to contain behaviour of two other objects containing the same methods.
some object pretending to be another object but actually is delegating the task to the real object

from wikipedia
In software engineering, the delegation pattern is a technique where an object outwardly expresses certain behaviour but in reality delegates responsibility for implementing that behavior to an associated object in an Inversion of Responsibility.
interface I {
void f();
void g();
}

class A implements I {
public void f() { System.out.println("A: doing f()"); }
public void g() { System.out.println("A: doing g()"); }
}

class B implements I {
public void f() { System.out.println("B: doing f()"); }
public void g() { System.out.println("B: doing g()"); }
}

class C implements I {
// delegation
I i = new A();

public void f() { i.f(); }
public void g() { i.g(); }

// normal attributes
void toA() { i = new A(); }
void toB() { i = new B(); }
}


public class Main {
public static void main(String[] args) {
C c = new C();
c.f();
c.g();
c.toB();
c.f();
c.g();
}
}
The object C changes behaviour by calling the method toB(). After calling toB() all methods of C reflect those of B.

Comments