Patterncore
Delegation pattern
Also called Delegation, delegate, delegation pattern, forwarding.
An object hands a request to a helper object, its delegate, and passes itself when the delegate needs it. This gives the reuse of inheritance through composition.
- Family
- structural-design
- Intent
- Let an object reuse the behaviour of another object by handing requests to it, in place of inheriting from its class, so that composition is as powerful for reuse as inheritance.
- Also called
- Delegate
Intent
Let an object reuse the behaviour of another object by handing requests to it, in place of inheriting from its class. Two objects handle each request: the receiving object, and its delegate.12
Problem
A Window needs an area. A Rectangle class already computes one. If Window inherits from Rectangle, every window is a rectangle for all of its life, and it gets every public method of Rectangle, also those that make no sense for a window. A round window then needs a second subclass, and a window that changes its shape cannot exist.
The forces are these:
- The new class needs some behaviour of an existing class, but it is not a kind of that class.
- The behaviour can change for one object, or at run time.
- The reused code sometimes needs to call back to the object that uses it.
Solution
Give the receiving object a field that holds the delegate. For each request that the delegate handles, the receiver calls the matching method of the delegate. When the delegate needs the receiver, the receiver passes itself as an argument.2
Client Window (receiver) Rectangle (delegate)
------ ----------------- --------------------
w.area() -------> shape.area() -------------------> width * height
w.describe() ---> shape.describe(self) -----------> uses owner.title
field: shape (can be replaced at run time)
Design Patterns describes delegation as a way to make composition as powerful for reuse as inheritance. With inheritance, an inherited operation can always refer to the receiving object through this or self. With delegation, the receiver passes itself to the delegate to get the same effect.21
Delegation and forwarding. The word "delegation" is often used for plain forwarding, where the receiver calls the delegate and the call runs in the context of the delegate only.1 In the strict sense, delegation evaluates a member of one object in the context of the original sender.3 Lieberman defined this sense in 1986 as a language feature, and Self and JavaScript support it in the language.3 A language without that support must pass the sender by hand.
Some languages generate the forwarding code:
| Language | Support |
|---|---|
| Kotlin | class Derived(b: Base) : Base by b generates every member of Base and forwards it to b4 |
| Go | an embedded field promotes its methods to the outer struct5 |
| JavaScript | a method found on the prototype runs with this set to the inheriting object6 |
| Python | __getattr__ runs when normal lookup fails, so it can forward every missing attribute7 |
| Rust | no forwarding keyword; Deref is meant for smart pointers, not for general delegation8 |
Example
The example files show one program in each language. A Window delegates area to a shape, and it delegates describe to the shape with itself as the argument, so that the shape can read the title of the window. Then the program replaces the rectangle with a triangle, and the same window changes its behaviour:
area: 12
main: a rectangle of 3 by 4
area: 6
main: a triangle of 3 by 4
Each example uses an interface or a protocol for the shape, so that Window does not depend on one class. The Go example embeds the Shape interface in the struct, so Area is a promoted method and needs no forwarding method.
In JavaScript, the prototype chain gives delegation with no code. The method is found on the prototype, but this is the object that received the call:6
const rectangle = {
describe() {
return `${this.title}: a rectangle`;
},
};
const window1 = Object.create(rectangle);
window1.title = "main";
console.log(window1.describe());
console.log(Object.hasOwn(window1, "describe"));
main: a rectangle
false
from typing import Protocol
class Window(Protocol):
title: str
class Shape(Protocol):
def area(self) -> int: ...
def describe(self, owner: Window) -> str: ...
class Rectangle:
def __init__(self, width: int, height: int) -> None:
self.width, self.height = width, height
def area(self) -> int:
return self.width * self.height
def describe(self, owner: Window) -> str:
return f"{owner.title}: a rectangle of {self.width} by {self.height}"
class Triangle:
def __init__(self, base: int, height: int) -> None:
self.base, self.height = base, height
def area(self) -> int:
return self.base * self.height // 2
def describe(self, owner: Window) -> str:
return f"{owner.title}: a triangle of {self.base} by {self.height}"
class AppWindow:
def __init__(self, title: str, shape: Shape) -> None:
self.title = title
self.shape = shape # the delegate
def area(self) -> int:
return self.shape.area() # forward
def describe(self) -> str:
return self.shape.describe(self) # delegate, and pass the receiver
w = AppWindow("main", Rectangle(3, 4))
print("area:", w.area())
print(w.describe())
w.shape = Triangle(3, 4) # change the behaviour at run time
print("area:", w.area())
print(w.describe())
area: 12
main: a rectangle of 3 by 4
area: 6
main: a triangle of 3 by 4
- Verdict: idiom. The window holds the shape in a field and calls it by hand.
- For a wrapper that forwards every attribute,
__getattr__runs only when normal lookup fails, so one method can forward all the missing names to the delegate.
#include <iostream>
#include <memory>
#include <string>
struct Titled {
virtual ~Titled() = default;
virtual std::string title() const = 0;
};
struct Shape {
virtual ~Shape() = default;
virtual int area() const = 0;
virtual std::string describe(const Titled& owner) const = 0;
};
struct Rectangle : Shape {
int width, height;
Rectangle(int w, int h) : width(w), height(h) {}
int area() const override { return width * height; }
std::string describe(const Titled& owner) const override {
return owner.title() + ": a rectangle of " + std::to_string(width) + " by " + std::to_string(height);
}
};
struct Triangle : Shape {
int base, height;
Triangle(int b, int h) : base(b), height(h) {}
int area() const override { return base * height / 2; }
std::string describe(const Titled& owner) const override {
return owner.title() + ": a triangle of " + std::to_string(base) + " by " + std::to_string(height);
}
};
class AppWindow : public Titled {
public:
AppWindow(std::string title, std::unique_ptr<Shape> shape)
: title_(std::move(title)), shape_(std::move(shape)) {}
std::string title() const override { return title_; }
void set_shape(std::unique_ptr<Shape> shape) { shape_ = std::move(shape); }
int area() const { return shape_->area(); } // forward
std::string describe() const { return shape_->describe(*this); } // delegate, and pass the receiver
private:
std::string title_;
std::unique_ptr<Shape> shape_; // the delegate
};
int main() {
AppWindow w("main", std::make_unique<Rectangle>(3, 4));
std::cout << "area: " << w.area() << "\n" << w.describe() << "\n";
w.set_shape(std::make_unique<Triangle>(3, 4)); // change the behaviour at run time
std::cout << "area: " << w.area() << "\n" << w.describe() << "\n";
}
area: 12
main: a rectangle of 3 by 4
area: 6
main: a triangle of 3 by 4
- Verdict: idiom. The window owns its delegate through a
std::unique_ptr, and replacing the pointer changes the behaviour.
interface Titled {
String title();
}
interface Shape {
int area();
String describe(Titled owner);
}
record Rectangle(int width, int height) implements Shape {
public int area() { return width * height; }
public String describe(Titled owner) {
return owner.title() + ": a rectangle of " + width + " by " + height;
}
}
record Triangle(int base, int height) implements Shape {
public int area() { return base * height / 2; }
public String describe(Titled owner) {
return owner.title() + ": a triangle of " + base + " by " + height;
}
}
class AppWindow implements Titled {
private final String title;
private Shape shape; // the delegate
AppWindow(String title, Shape shape) {
this.title = title;
this.shape = shape;
}
public String title() { return title; }
void setShape(Shape shape) { this.shape = shape; }
int area() { return shape.area(); } // forward
String describe() { return shape.describe(this); } // delegate, and pass the receiver
}
public class Main {
public static void main(String[] args) {
AppWindow w = new AppWindow("main", new Rectangle(3, 4));
System.out.println("area: " + w.area());
System.out.println(w.describe());
w.setShape(new Triangle(3, 4)); // change the behaviour at run time
System.out.println("area: " + w.area());
System.out.println(w.describe());
}
}
area: 12
main: a rectangle of 3 by 4
area: 6
main: a triangle of 3 by 4
- Verdict: idiom. Java has no forwarding keyword, so each delegated method is written by hand.
using System;
interface ITitled
{
string Title { get; }
}
interface IShape
{
int Area();
string Describe(ITitled owner);
}
record Rectangle(int Width, int Height) : IShape
{
public int Area() => Width * Height;
public string Describe(ITitled owner) => $"{owner.Title}: a rectangle of {Width} by {Height}";
}
record Triangle(int Base, int Height) : IShape
{
public int Area() => Base * Height / 2;
public string Describe(ITitled owner) => $"{owner.Title}: a triangle of {Base} by {Height}";
}
class AppWindow : ITitled
{
public string Title { get; }
public IShape Shape { get; set; } // the delegate
public AppWindow(string title, IShape shape)
{
Title = title;
Shape = shape;
}
public int Area() => Shape.Area(); // forward
public string Describe() => Shape.Describe(this); // delegate, and pass the receiver
}
class Program
{
static void Main()
{
var w = new AppWindow("main", new Rectangle(3, 4));
Console.WriteLine($"area: {w.Area()}");
Console.WriteLine(w.Describe());
w.Shape = new Triangle(3, 4); // change the behaviour at run time
Console.WriteLine($"area: {w.Area()}");
Console.WriteLine(w.Describe());
}
}
area: 12
main: a rectangle of 3 by 4
area: 6
main: a triangle of 3 by 4
- Verdict: idiom. The window holds the delegate in a property of an interface type, and each forwarded method is one expression.
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
area() {
return this.width * this.height;
}
describe(owner) {
return `${owner.title}: a rectangle of ${this.width} by ${this.height}`;
}
}
class Triangle {
constructor(base, height) {
this.base = base;
this.height = height;
}
area() {
return Math.floor((this.base * this.height) / 2);
}
describe(owner) {
return `${owner.title}: a triangle of ${this.base} by ${this.height}`;
}
}
class AppWindow {
constructor(title, shape) {
this.title = title;
this.shape = shape; // the delegate
}
area() {
return this.shape.area(); // forward
}
describe() {
return this.shape.describe(this); // delegate, and pass the receiver
}
}
const w = new AppWindow("main", new Rectangle(3, 4));
console.log("area:", w.area());
console.log(w.describe());
w.shape = new Triangle(3, 4); // change the behaviour at run time
console.log("area:", w.area());
console.log(w.describe());
area: 12
main: a rectangle of 3 by 4
area: 6
main: a triangle of 3 by 4
- Verdict: native for prototypes, idiom for classes. A method found on the prototype runs with
thisset to the object that received the call, which is delegation in the strict sense. Between two class instances, the window forwards by hand, as here.
interface Titled {
readonly title: string;
}
interface Shape {
area(): number;
describe(owner: Titled): string;
}
class Rectangle implements Shape {
private width: number;
private height: number;
constructor(width: number, height: number) {
this.width = width;
this.height = height;
}
area(): number {
return this.width * this.height;
}
describe(owner: Titled): string {
return `${owner.title}: a rectangle of ${this.width} by ${this.height}`;
}
}
class Triangle implements Shape {
private base: number;
private height: number;
constructor(base: number, height: number) {
this.base = base;
this.height = height;
}
area(): number {
return Math.floor((this.base * this.height) / 2);
}
describe(owner: Titled): string {
return `${owner.title}: a triangle of ${this.base} by ${this.height}`;
}
}
class AppWindow implements Titled {
readonly title: string;
shape: Shape; // the delegate
constructor(title: string, shape: Shape) {
this.title = title;
this.shape = shape;
}
area(): number {
return this.shape.area(); // forward
}
describe(): string {
return this.shape.describe(this); // delegate, and pass the receiver
}
}
const w = new AppWindow("main", new Rectangle(3, 4));
console.log("area:", w.area());
console.log(w.describe());
w.shape = new Triangle(3, 4); // change the behaviour at run time
console.log("area:", w.area());
console.log(w.describe());
area: 12
main: a rectangle of 3 by 4
area: 6
main: a triangle of 3 by 4
- Verdict: idiom. The delegate has the interface type
Shape, so any class with the two methods can take its place. - The delegate sees the receiver only through the small
Titledinterface, not the wholeAppWindowclass.
package main
import "fmt"
type Titled interface {
Title() string
}
type Shape interface {
Area() int
Describe(owner Titled) string
}
type Rectangle struct{ Width, Height int }
func (r Rectangle) Area() int { return r.Width * r.Height }
func (r Rectangle) Describe(owner Titled) string {
return fmt.Sprintf("%s: a rectangle of %d by %d", owner.Title(), r.Width, r.Height)
}
type Triangle struct{ Base, Height int }
func (t Triangle) Area() int { return t.Base * t.Height / 2 }
func (t Triangle) Describe(owner Titled) string {
return fmt.Sprintf("%s: a triangle of %d by %d", owner.Title(), t.Base, t.Height)
}
// AppWindow embeds the Shape interface. Area is promoted, so it needs no
// forwarding method.
type AppWindow struct {
Shape
title string
}
func (w *AppWindow) Title() string { return w.title }
// Describe passes the receiver to the delegate.
func (w *AppWindow) Describe() string { return w.Shape.Describe(w) }
func main() {
w := &AppWindow{Shape: Rectangle{3, 4}, title: "main"}
fmt.Println("area:", w.Area())
fmt.Println(w.Describe())
w.Shape = Triangle{3, 4} // change the behaviour at run time
fmt.Println("area:", w.Area())
fmt.Println(w.Describe())
}
area: 12
main: a rectangle of 3 by 4
area: 6
main: a triangle of 3 by 4
- Verdict: native for forwarding. An embedded field promotes its methods to the outer struct, so
w.Area()calls theAreaof the shape. - Embedding is forwarding, not delegation in the strict sense: inside
Rectangle.Area, the receiver is the rectangle, not the window.Describepasses the window by hand.
trait Titled {
fn title(&self) -> &str;
}
trait Shape {
fn area(&self) -> i32;
fn describe(&self, owner: &dyn Titled) -> String;
}
struct Rectangle {
width: i32,
height: i32,
}
impl Shape for Rectangle {
fn area(&self) -> i32 {
self.width * self.height
}
fn describe(&self, owner: &dyn Titled) -> String {
format!("{}: a rectangle of {} by {}", owner.title(), self.width, self.height)
}
}
struct Triangle {
base: i32,
height: i32,
}
impl Shape for Triangle {
fn area(&self) -> i32 {
self.base * self.height / 2
}
fn describe(&self, owner: &dyn Titled) -> String {
format!("{}: a triangle of {} by {}", owner.title(), self.base, self.height)
}
}
struct AppWindow {
title: String,
shape: Box<dyn Shape>, // the delegate
}
impl Titled for AppWindow {
fn title(&self) -> &str {
&self.title
}
}
impl AppWindow {
fn area(&self) -> i32 {
self.shape.area() // forward
}
fn describe(&self) -> String {
self.shape.describe(self) // delegate, and pass the receiver
}
}
fn main() {
let mut w = AppWindow { title: "main".to_string(), shape: Box::new(Rectangle { width: 3, height: 4 }) };
println!("area: {}", w.area());
println!("{}", w.describe());
w.shape = Box::new(Triangle { base: 3, height: 4 }); // change the behaviour at run time
println!("area: {}", w.area());
println!("{}", w.describe());
}
area: 12
main: a rectangle of 3 by 4
area: 6
main: a triangle of 3 by 4
- Verdict: idiom. Rust has no inheritance and no forwarding keyword, so the window writes each forwarding method. A
Box<dyn Shape>lets the delegate change at run time.
Consequences
The main benefit is that the behaviour can change at run time. Design Patterns gives the same example: a window becomes circular when it replaces its rectangle with a circle, if both have the same type.2 The receiver also shows only the methods it chooses, not every method of the reused class.
The costs:
- More code. Each forwarded method is a method that someone must write and keep in step with the delegate, unless the language generates it.4
- Harder to follow. Design Patterns warns that dynamic, highly parameterized software is harder to understand than static software, and that delegation has a cost at run time. It calls delegation a good design choice only when it simplifies more than it complicates.2
- The self problem. Plain forwarding loses the sender. If the delegate calls one of its own methods, it calls its own version, not the override of the receiver. The Kotlin documentation says this of
by: members that the class overrides do not get called from the members of the delegate.4
Here the window overrides name, but the delegate calls its own name:
This code runs but gives a wrong answer on purpose.
class Rectangle:
def name(self):
return "rectangle"
def describe(self):
return f"a {self.name()}"
class Window:
def __init__(self, shape):
self.shape = shape
def name(self):
return "window"
def describe(self):
return self.shape.describe() # forwarding: self in the delegate is the shape
print(Window(Rectangle()).describe())
a rectangle
The fix is to pass the receiver, so that the delegate calls back through it. This is the form that Design Patterns describes:2
class Rectangle:
def name(self):
return "rectangle"
def describe(self, owner):
return f"a {owner.name()}"
class Window:
def __init__(self, shape):
self.shape = shape
def name(self):
return "window"
def describe(self):
return self.shape.describe(self)
print(Window(Rectangle()).describe())
a window
When not to use it
Do not delegate when the new class really is a kind of the old class and must be used where the old class is expected. Inheritance, or an interface that both classes implement, states that relation more directly.
Do not forward a large interface by hand when only one or two methods change. The forwarding code hides the methods that matter. Use a language feature such as Kotlin by or Go embedding, or reconsider the design.
Do not use Deref in Rust to imitate inheritance. The standard library advises to implement it only when the type transparently behaves like the target type, and not when the type has methods that are likely to collide with those of the target.8
Variants and related patterns
Forwarding. The receiver calls the delegate and does not pass itself. Most uses of the word "delegation" mean this form.1
Language-level delegation. In prototype-based languages, delegation is the main way to reuse behaviour, as inheritance is in class-based languages.3 See Prototype-based programming.
Patterns built on delegation. Design Patterns names State, Strategy and Visitor as patterns that depend on delegation.2 A Strategy pattern is a delegate that the client picks. A Decorator pattern and a Proxy pattern forward to an object with the same interface, and add or control behaviour.
Composition over inheritance. Delegation is the mechanism behind the principle of Composition over inheritance.
Known uses
- Go: bufio/bufio.go at go1.25.0 defines
ReadWriteras a struct that embeds a*Readerand a*Writer. The embedded fields promote their methods, so aReadWriterimplementsio.ReadWriterwith no forwarding methods.95 - Python: Lib/tempfile.py at v3.14.0 wraps a file in
_TemporaryFileWrapper. Its__getattr__delegates attribute lookups to the underlying file, and caches the methods it finds.107
References
- Delegation pattern, Wikipedia, Introduction; Definition; Language support
- Gamma, Helm, Johnson and Vlissides, Design Patterns, Elements of Reusable Object-Oriented Software, Addison-Wesley, 1994, Chapter 1, Introduction, Delegation (pages 20 and 21)
- Delegation (object-oriented programming), Wikipedia, Introduction; Overview; Language support for delegation
- Delegation, Kotlin Documentation, Delegation; Overriding a member of an interface implemented by delegation
- The Go Programming Language Specification, Struct types (embedded fields and promoted methods)
- Inheritance and the prototype chain, MDN Web Docs, Introduction; Inheriting "methods"
- The Python Language Reference, Data model, Python 3.14, object.__getattr__
- Deref, The Rust Standard Library, When to implement Deref or DerefMut
- Go go1.25.0 source, src/bufio/bufio.go, ReadWriter and NewReadWriter, lines 835 to 845
- CPython v3.14.0 source, Lib/tempfile.py, _TemporaryFileWrapper and its __getattr__, lines 487 to 527
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag FHMA2X Edit this page History Report an error Markdown