Delegation (object-oriented programming)

From LabVIEW Wiki
(Redirected from Delegation pattern)
Jump to: navigation, search

In object-oriented programming, delegation (sometimes referred to as delegation pattern) allows one object (the delegate) to operate on behalf of another object (the delegator) without the need for a common ancestor. Instead of inheriting methods from a common ancestor, the delegator uses object composition to reuse functionality of the delegate. In programming languages that don't have native support for object delegation, the delegator may pass itself to the delegate to let it operate on behalf of the delegator. Alternatively, the delegator can keep an instance of the delegate in its private data and forward any delegate-specific behavior to it.

Use case example

Classes Rectangle, Square, Circle and Triangle inherit from a common ancestor Surface, which has a method Area to calculate the surface area.

After closer inspection, the formulas for Rectangle, Square and Triangle are very similar and should reuse common functionality:

Class Equation
Rectangle a * b
Square a * a
Triangle a * b / 2
Circle PI*r^2

Solution using inheritance

Square and Triangle inherit from Rectangle, which implements the common functionality. In this case, Triangle needs to override the Area method in order to complete its equation.

This solution is considered bad practice, because Triangle is not a Rectangle; the equation only happens to be based on rectangles. It also adds another layer of inheritance, which might not be desirable and can be problematic if classes require distinct behavior in the future.

Solution using delegation

Square and Triangle use object composition to delegate some of their work to Rectangle. In this case, both Square and Triangle keep their own instance of Rectangle in their private data and delegate any Rectangle-specific behavior to it.

This solution requires extra work to implement, but if requirements change in the future, Rectangle can always be removed from either Square and Triangle without affecting any other classes.

External links