<<Up     Contents

Delegation pattern

The delegation pattern is a technique that simulates mixins, delegation, and some kinds of aspects in traditional object-oriented languages like C++ and Java.

Table of contents

Simple Java Example

In this example, the class C has method stubs that forward the methods f() and g() to class A. Class C pretends that it has attributes of class A.

  class A {
    void f() { system.out.println("A: doing f()"); }
    void g() { system.out.println("A: doing g()"); }
  }

  class C {
    // delegation
    A a = new A();

    void f() { a.f(); }
    void g() { a.g(); }

    // normal attributes
    X x = new X();
    void y() { /* do stuff */ }
  }

  void main() {
    C c = new C();

    c.f();
    c.g();
  }

Complex Java Example

By using interfaces, delegation can be made more flexible and typesafe. In this example, class C can delegate to either class A or class B. Class C has methods to switch between classes A and B. Including the implements clauses improves type safety, because each class must implement the methods in the interface. The main tradeoff is more code.

  interface I {
    void f();
    void g();
  }

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

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

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

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

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

  void main() {
    C c = new C();

    c.f();
    c.g();
  }

Criticisms

Because this is a pattern, developers can make many kinds of mistakes. The developer could forget method in the simple version. The developer could mistype the name of one attribute.

This pattern does not work with variable attributes, which need get and set methods.

Optimization is harder, because spelling details out in the source code complicates analysis.

References

See also Design pattern and Post-object programming.

wikipedia.org dumped 2003-03-17 with terodump