Delegation patternIn 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). The delegate is a helper object, but with the original context. With language-level support for delegation, this is done implicitly by having 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. DefinitionIn the Introduction to Gamma et al. 1994, delegation is defined as:
ExampleIn the example below (using the Kotlin programming language), the class Window delegates the class Rectangle(val width: Int, val height: Int) {
fun area() = width * height
}
class Window(val bounds: Rectangle) {
// Delegation
fun area() = bounds.area()
}
Language supportSome languages have special support for delegation built in. For example, in the Kotlin programming language the interface ClosedShape {
fun area(): Int
}
class Rectangle(val width: Int, val height: Int) : ClosedShape {
override fun area() = width * height
}
// The ClosedShape implementation of Window delegates to that of the Rectangle that is bounds
class Window(private val bounds: Rectangle) : ClosedShape by bounds
See also
References
External links
|
Portal di Ensiklopedia Dunia