Skip to main content
查利博客

Delegation vs. Forwarding

The Delegation Pattern is an object-oriented design pattern that uses object composition to achieve the code reuse without inheritance. It is often mixed up with the concept of forwarding. The difference between them is that the self or this refers to which objects. Generally speaking, both delegation and forwarding involves two objects: the sender / wrapper object and the receiver / wrappee object. It is said to be a delegation if this bounds to the sender object, while in forwarding refers to the receiver object.

Forwarding Example #

Sender:

public class Sender {
  Receiver receiver;

  public Sender(Receiver receiver) {
    this.receiver = receiver;
  }

  public void foo() {
    receiver.foo();
  }
}

Receiver:

public class Receiver {
  public void foo() {
    System.out.println(this);
  }
}

Client:

public class ForwardingExample {
  public static void main(String[] args) {
    Sender sender = new Sender(new Receiver());
    sender.foo();
  }
}

Output:

com.caizhenhua.javase.designpattern.forwarding.Receiver@251a69d7

Delegation Example #

Sender:

public class Sender {
  Receiver receiver;

  public Sender(Receiver receiver) {
    this.receiver = receiver;
  }

  // pass the wrapper object to the wrappee
  public void foo() {
    receiver.foo(this);
  }

  public void bar() {
    System.out.println(this);
  }
}

Receiver:

public class Receiver {
  Sender sender;

  public void foo(Sender sender) {
    this.sender = sender;
    this.bar();
  }

  public void bar() {
    sender.bar();
  }
}

Client:

public class DelegationExample {
  public static void main(String[] args) {
    Sender sender = new Sender(new Receiver());
    sender.foo();
  }
}

Output:

com.caizhenhua.javase.designpattern.delegation.Sender@251a69d7

Delegation By Inheritance Example #

Sender:

public class Sender {
  public void bar() {
    System.out.println(this);
  }
}

Receiver:

public class Receiver extends Sender {
  @Override
  public void bar() {
    super.bar();
    System.out.println(this);
  }
}

Client:

public class DelegationByInheritanceExample {
  public static void main(String[] args) {
    new Receiver().bar();
  }
}

Output:

com.caizhenhua.javase.designpattern.inheritance.delegation.Receiver@251a69d7
com.caizhenhua.javase.designpattern.inheritance.delegation.Receiver@251a69d7