Delegation pattern


In software engineering, the delegation pattern is an object-oriented design pattern that allows object composition to achieve the same code reuse as inheritance.
In delegation, an object handles a request by delegating to a second object. The delegate is a helper object, but with the original context. With language-level support for delegation, this is done implicitly by having self in the delegate refer to the original object, not the delegate. In the delegate pattern, this is instead accomplished by explicitly passing the original object to the delegate, as an argument to a method. Note that "delegation" is often used loosely to refer to the distinct concept of forwarding, where the sending object simply uses the corresponding member on the receiving object, evaluated in the context of the receiving object, not the original object.
Note that this article uses "sending object/receiving object" for the two objects, rather than "receiving object/delegate", emphasizing which objects send and receive the delegation call, not the original call.

Definition

In the Introduction to Gamma et al. 1994, Grady Booch defined delegation as:

Example

In the example below, the class Window delegates the area call to its internal Rectangle object.
class Rectangle
class Window

Language support

Some languages have special support for delegation built in. For example, in the Kotlin programming language, we could write:
interface ClosedShape
class Rectangle : ClosedShape
class Window : ClosedShape by bounds