Jump to content

Delegation pattern

From Wikipedia, the free encyclopedia

This is an old revision of this page, as edited by Nbarth (talk | contribs) at 04:58, 11 April 2016 (External links: c2 link). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

In software engineering, the delegation pattern is a design pattern in object-oriented programming that implements delegation in languages without language-level support, allowing 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 (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 (sending) object, not the delegate (receiving object). In the delegate pattern, this is instead accomplished by explicitly passing the original object to the delegate, as an argument to a method.[1] 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.

Definition

In Gemma et al. 1994, delegation is defined as:

Delegation is a way to make composition as powerful for reuse as inheritance [Lie86, JZ91]. In delegation, two objects are involved in handling a request: a receiving object delegates operations to its delegate. This is analogous to subclasses deferring requests to parent classes. But with inheritance, an inherited operation can always refer to the receiving object through the this member variable in C++ and self in Smalltalk. To achieve the same effect with delegation, the receiver passes itself to the delegate to let the delegated operation refer to the receiver.

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.

See also

References

  1. ^ Gemma et al. 1994