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). 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 (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] "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.

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, 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.[2]

Example

In the example below (using the Kotlin programming language), the class Window delegates the area() call to its internal Rectangle object (its delegate).

class Rectangle(val width: Int, val height: Int) {
    fun area() = width * height
}

class Window(val bounds: Rectangle) {
    // Delegation
    fun area() = bounds.area()
}

Language support

Some languages have special support for delegation built in. For example, in the Kotlin programming language the by keyword[3] delegates to another object's interface:

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

A more practical example is the following:

  interface Repository {
      fun save(data: String)
      fun load(id: String): String
      fun delete(id: String)
  }

  class FileRepository : Repository {
      override fun save(data: String) = println("saving $data")
      override fun load(id: String): String = "data:$id"
      override fun delete(id: String) = println("deleting $id")
  }

  class LoggingRepository(
      private val delegate: Repository
  ) : Repository by delegate {
      override fun save(data: String) {
          println("about to save")
          delegate.save(data)
      }
  }

In this example, LoggingRepository implements the same interface as Repository, while wrapping another Repository instance. The save method is specialized to add logging, whereas the remaining methods are forwarded automatically to the delegate object.

This avoids boilerplate and makes it possible to extend the behavior of a Repository without being tied to a particular concrete implementation such as FileRepository. By contrast, an inheritance-based solution would require subclassing a specific implementation:

  interface Repository {
      fun save(data: String)
      fun load(id: String): String
      fun delete(id: String)
  }

  open class FileRepository : Repository {
      override fun save(data: String) = println("saving $data")
      override fun load(id: String): String = "data:$id"
      override fun delete(id: String) = println("deleting $id")
  }

  class LoggingRepository : FileRepository() {
      override fun save(data: String) {
          println("about to save")
          super.save(data)
      }
  }

This approach couples LoggingRepository to FileRepository, whereas interface delegation allows the same wrapper to be used with any `Repository` implementation.

In Kotlin, interface delegation using by is implemented by the compiler through generated forwarding methods. For example, the previous Window class is equivalent to code such as:

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 {
    override fun area() = bounds.area()
}

When interface delegation is combined with manual overriding, only the members not explicitly overridden are forwarded automatically. For example:

interface Greeter {
      fun greet()
      fun greetTwice()
  }

  class DefaultGreeter : Greeter {
      override fun greet() {
          println("hello")
      }

      override fun greetTwice() {
          greet()
          greet()
      }
  }

  class LoudGreeter(
      private val delegate: Greeter
  ) : Greeter by delegate {
      override fun greet() {
          println("HELLO")
      }
  }

fun main() {
      val g = LoudGreeter(DefaultGreeter())

      g.greet()
      g.greetTwice()
}

This program will print

HELLO
hello
hello

The result shows that greet is handled by the explicit override in LoudGreeter, whereas greetTwice is forwarded to DefaultGreeter. Inside DefaultGreeter.greetTwice, the receiver remains the delegate object itself, so the internal calls to greet() resolve to DefaultGreeter.greet() rather than LoudGreeter.greet().

For this reason, Kotlin's by feature is often described as delegation, but operationally it is closer to compiler-generated forwarding than to stronger forms of delegation in which the original receiver context is preserved.[4]

See also

References

  1. ^ Gamma et al. 1994
  2. ^ Gamma, Erich; Helm, Richard; Johnson, Ralph; Vlissides, John (1995). Design patterns : elements of reusable object-oriented software (14. print. ed.). Reading, Mass.: Addison-Wesley. p. 20. ISBN 0-201-63361-2.
  3. ^ "Delegation - Kotlin Programming Language". Kotlin. Retrieved 2019-03-23.
  4. ^ https://en.wikipedia.org/wiki/Delegation_(object-oriented_programming)