| |||||||||
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. This simulates mixins, delegation, and some kinds of aspects in traditional object-oriented languages like C++ and Java. Aggregation must be used with it if inheritance is not applicable.
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.
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.
Because this is a pattern, developers can make many kinds of mistakes. The developer could forget to delegate a method in the simple version. The developer could mistype the name of one attribute.
This pattern typically sacrifices speed optimization in favour of enhanced clarity of abstraction.
See also Design pattern and Post-object programming.