Programming Search⌘K

Patterncore

Decorator pattern

Also called Decorator, wrapper.

A decorator wraps an object, has the same interface, and adds behaviour before or after it forwards each call. Decorators stack, so features combine at run time without a subclass for each mix.

Family
structural-design
Intent
Add a responsibility to one object at run time by wrapping it in an object with the same interface, as a flexible alternative to subclassing.
Also called
Wrapper
Refactorings
Move embellishment to decorator

Intent

Add a responsibility to one object at run time. Wrap the object in another object with the same interface, which does its own work and forwards the call. This is a flexible alternative to a subclass.1

Problem

A repository loads values by key from a slow store. Some callers need the calls logged. Some need the results cached. Some need both, and a test needs neither. Later someone will ask for retries and for a timer.

The direct design adds a subclass for each feature: LoggedStore, CachedStore. But the features combine. Logging and caching together need a third class, and with retries and a timer the number of classes grows with each combination. A subclass also fixes the feature when the code is written. It cannot add caching to one store object at run time. Nor can it add caching to a class that the program did not write, such as a class from a library or a final class.

The other direct design puts all the features in the store, behind flags. Then every store carries the code for every feature, and the store's main job, loading values, is hard to find. Kerievsky describes this starting point: code adds an embellishment to the core responsibility of a class.2

The forces are these. Features must combine in any order and number. They must be added to single objects, at run time. The code that uses the object must not know which features are there. The core class must not change.

Solution

Make each feature a class that implements the same interface as the core object and holds a reference to a component of that interface. Each operation does its feature work and forwards the call to the component.1

 Component (Repository)  <----------------------------+
 ----------------------                               |
 get(key)                                             | holds one
 name()                                               |
      ^                                               |
      |                                               |
 +----+--------+---------------------+                |
 |             |                     |                |
 Store    Logged(inner)         Cached(inner) --------+
          get: log, then        get: if in cache, return it;
               inner.get(key)        else inner.get(key), store it
          name: inner.name()    name: inner.name()

 Logged(Cached(Store())).get("a")
   Logged.get --> Cached.get --> Store.get

The participants in Design Patterns are the Component interface, the ConcreteComponent, the Decorator, which holds the component and forwards to it, and the ConcreteDecorators.1 A client builds a chain at run time: Logged(Cached(Store())). Each decorator sees only the interface of the next object, so any decorator can wrap any component or any other decorator.

The forwarding has two parts. Every operation of the interface must forward, even the ones that the decorator does not change. The decorator can do its work before the call, as with logging or a check. It can work after the call, as when it stores a result. Or it can work in place of the call, as when it returns a cached result.

Streams are the classic case. Design Patterns names streams as a known use.1 java.io.FilterInputStream wraps some other input stream, which it uses as its basic source of data, and passes requests to the wrapped stream. BufferedInputStream is one of its subclasses, and adds a buffer to another input stream.34 Python io.BufferedReader gives buffered access to a raw binary stream. .NET BufferedStream adds a buffer to another stream, and Rust BufReader adds buffering to any reader.5108 Go HTTP middleware has the same shape: http.StripPrefix takes a handler and returns a handler that changes the request path and calls the first.6

In languages with first-class functions, a decorator of one operation is a higher-order function. It takes a function and returns a function with the same signature. Python functools.cache is a decorator in this sense: it wraps a function and stores its results.14 When the interface has many operations, the class form is still needed, because each operation must forward.

Example

The example files show one program in each language. The store prints store: load a and returns value-a. The chain is Logged(Cached(Store())). The program calls get("a") twice and get("b") once, and then prints name(). The second call for a is logged but does not reach the store. The decorators do not change name(), so they forward it, and it prints store.

Language Form
Python classes with a typing.Protocol for the interface
JavaScript classes that hold the inner object
TypeScript an interface and classes that implement it
Java an interface and final classes, as in java.io
Kotlin class delegation with by, so only get is written by hand
C# an interface and sealed classes
Go a struct that embeds the interface, so Name is promoted
Rust generic wrappers over a trait
C++ an abstract class and wrappers that own the inner object through std::unique_ptr
PythonGitHub
from typing import Protocol


class Repository(Protocol):
    def get(self, key: str) -> str: ...
    def name(self) -> str: ...


class Store:
    def get(self, key: str) -> str:
        print(f"store: load {key}")
        return f"value-{key}"

    def name(self) -> str:
        return "store"


class Logged:
    def __init__(self, inner: Repository) -> None:
        self.inner = inner

    def get(self, key: str) -> str:
        print(f"log: get {key}")
        return self.inner.get(key)

    def name(self) -> str:
        return self.inner.name()


class Cached:
    def __init__(self, inner: Repository) -> None:
        self.inner = inner
        self.cache: dict[str, str] = {}

    def get(self, key: str) -> str:
        if key not in self.cache:
            self.cache[key] = self.inner.get(key)
        return self.cache[key]

    def name(self) -> str:
        return self.inner.name()


repo: Repository = Logged(Cached(Store()))
for key in ["a", "a", "b"]:
    print(repo.get(key))
print(f"name: {repo.name()}")
Output
log: get a
store: load a
value-a
log: get a
value-a
log: get b
store: load b
value-b
name: store
  • Verdict: idiom. Python has no decorator construct of the Design Patterns kind, so the pattern is two classes that hold the inner object and forward to it.
  • typing.Protocol states the interface for a type checker. The classes do not inherit from it. At run time any object with get and name works.
  • The @ syntax of Python is a different construct with the same name. It applies a function to a function or a class when the code defines it. The node page shows functools.wraps and functools.cache used this way.
  • A __getattr__ method that returns getattr(self.inner, name) forwards every attribute that the class does not define, so name would not need to be written. The cost is that a type checker cannot see the forwarded methods.
#include <iostream>
#include <map>
#include <memory>
#include <string>

class Repository {
public:
    virtual ~Repository() = default;
    virtual std::string get(const std::string& key) = 0;
    virtual std::string name() const = 0;
};

class Store : public Repository {
public:
    std::string get(const std::string& key) override {
        std::cout << "store: load " << key << "\n";
        return "value-" + key;
    }
    std::string name() const override { return "store"; }
};

class Logged : public Repository {
public:
    explicit Logged(std::unique_ptr<Repository> inner) : inner_(std::move(inner)) {}
    std::string get(const std::string& key) override {
        std::cout << "log: get " << key << "\n";
        return inner_->get(key);
    }
    std::string name() const override { return inner_->name(); }

private:
    std::unique_ptr<Repository> inner_;
};

class Cached : public Repository {
public:
    explicit Cached(std::unique_ptr<Repository> inner) : inner_(std::move(inner)) {}
    std::string get(const std::string& key) override {
        auto it = cache_.find(key);
        if (it != cache_.end()) {
            return it->second;
        }
        std::string value = inner_->get(key);
        cache_.emplace(key, value);
        return value;
    }
    std::string name() const override { return inner_->name(); }

private:
    std::unique_ptr<Repository> inner_;
    std::map<std::string, std::string> cache_;
};

int main() {
    std::unique_ptr<Repository> repo =
        std::make_unique<Logged>(std::make_unique<Cached>(std::make_unique<Store>()));
    for (const char* key : {"a", "a", "b"}) {
        std::cout << repo->get(key) << "\n";
    }
    std::cout << "name: " << repo->name() << "\n";
}
Output
log: get a
store: load a
value-a
log: get a
value-a
log: get b
store: load b
value-b
name: store
  • Verdict: idiom. The decorators derive from the abstract class Repository and own the inner object through std::unique_ptr. When the outer decorator is destroyed, the whole chain is destroyed.
  • The virtual destructor makes it safe to destroy a Store through a pointer to Repository.
  • The chain can be known at compile time. Then a template Logged<Inner> that holds Inner by value removes the virtual calls, as in the Rust example.
JavaGitHub
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Main {
    interface Repository {
        String get(String key);

        String name();
    }

    static final class Store implements Repository {
        public String get(String key) {
            System.out.println("store: load " + key);
            return "value-" + key;
        }

        public String name() {
            return "store";
        }
    }

    static final class Logged implements Repository {
        private final Repository inner;

        Logged(Repository inner) {
            this.inner = inner;
        }

        public String get(String key) {
            System.out.println("log: get " + key);
            return inner.get(key);
        }

        public String name() {
            return inner.name();
        }
    }

    static final class Cached implements Repository {
        private final Repository inner;
        private final Map<String, String> cache = new HashMap<>();

        Cached(Repository inner) {
            this.inner = inner;
        }

        public String get(String key) {
            String value = cache.get(key);
            if (value == null) {
                value = inner.get(key);
                cache.put(key, value);
            }
            return value;
        }

        public String name() {
            return inner.name();
        }
    }

    public static void main(String[] args) {
        Repository repo = new Logged(new Cached(new Store()));
        for (String key : List.of("a", "a", "b")) {
            System.out.println(repo.get(key));
        }
        System.out.println("name: " + repo.name());
    }
}
Output
log: get a
store: load a
value-a
log: get a
value-a
log: get b
store: load b
value-b
name: store
  • Verdict: idiom. This is the form of Design Patterns: an interface, a concrete component, and decorators that implement the interface and hold a reference to it.
  • The classes are final. A decorator does not need to extend the class it wraps, so it can wrap a final class such as Store.
  • java.io uses the same form. FilterInputStream holds the wrapped stream in a field and forwards to it, and BufferedInputStream extends it to add a buffer.
  • cache.computeIfAbsent(key, inner::get) is shorter. The explicit form is used here to keep each step visible.
#include <stdio.h>
#include <string.h>

/* The interface: a table of function pointers and a pointer to the object. */
typedef struct Repository Repository;
struct Repository {
    void (*get)(Repository *self, const char *key, char *out, size_t size);
    const char *(*name)(Repository *self);
};

static void store_get(Repository *self, const char *key, char *out, size_t size) {
    (void)self;
    printf("store: load %s\n", key);
    snprintf(out, size, "value-%s", key);
}

static const char *store_name(Repository *self) {
    (void)self;
    return "store";
}

/* The Repository member comes first, so a pointer to it is a pointer to the decorator. */
typedef struct {
    Repository base;
    Repository *inner;
} Logged;

static void logged_get(Repository *self, const char *key, char *out, size_t size) {
    Logged *logged = (Logged *)self;
    printf("log: get %s\n", key);
    logged->inner->get(logged->inner, key, out, size);
}

static const char *logged_name(Repository *self) {
    Logged *logged = (Logged *)self;
    return logged->inner->name(logged->inner);
}

enum { SLOTS = 8, KEY_SIZE = 16, VALUE_SIZE = 32 };

typedef struct {
    Repository base;
    Repository *inner;
    int count;
    char keys[SLOTS][KEY_SIZE];
    char values[SLOTS][VALUE_SIZE];
} Cached;

static void cached_get(Repository *self, const char *key, char *out, size_t size) {
    Cached *cached = (Cached *)self;
    for (int i = 0; i < cached->count; i++) {
        if (strcmp(cached->keys[i], key) == 0) {
            snprintf(out, size, "%s", cached->values[i]);
            return;
        }
    }
    cached->inner->get(cached->inner, key, out, size);
    if (cached->count < SLOTS) {
        snprintf(cached->keys[cached->count], KEY_SIZE, "%s", key);
        snprintf(cached->values[cached->count], VALUE_SIZE, "%s", out);
        cached->count++;
    }
}

static const char *cached_name(Repository *self) {
    Cached *cached = (Cached *)self;
    return cached->inner->name(cached->inner);
}

int main(void) {
    Repository store = {store_get, store_name};
    Cached cached = {{cached_get, cached_name}, &store, 0, {{0}}, {{0}}};
    Logged logged = {{logged_get, logged_name}, &cached.base};
    Repository *repo = &logged.base;

    const char *keys[] = {"a", "a", "b"};
    char value[VALUE_SIZE];
    for (size_t i = 0; i < sizeof keys / sizeof keys[0]; i++) {
        repo->get(repo, keys[i], value, sizeof value);
        printf("%s\n", value);
    }
    printf("name: %s\n", repo->name(repo));
    return 0;
}
Output
log: get a
store: load a
value-a
log: get a
value-a
log: get b
store: load b
value-b
name: store
  • Verdict: idiom. C has no interfaces, so the interface is a struct of function pointers. Each decorator puts that struct first and adds a pointer to the inner object.
  • The cast from Repository * to Logged * is valid. A pointer to a structure, suitably converted, points to its first member, and the reverse also holds.
  • The compiler does not check that each decorator fills every function pointer. A missing one is a null pointer, and the call crashes at run time.
  • The objects live on the stack of main, so the program does not allocate. A chain built at run time needs malloc and a matching function to free it.
IRepository repo = new Logged(new Cached(new Store()));
foreach (var key in new[] { "a", "a", "b" })
{
    Console.WriteLine(repo.Get(key));
}
Console.WriteLine($"name: {repo.Name()}");

interface IRepository
{
    string Get(string key);
    string Name();
}

sealed class Store : IRepository
{
    public string Get(string key)
    {
        Console.WriteLine($"store: load {key}");
        return $"value-{key}";
    }

    public string Name() => "store";
}

sealed class Logged(IRepository inner) : IRepository
{
    public string Get(string key)
    {
        Console.WriteLine($"log: get {key}");
        return inner.Get(key);
    }

    public string Name() => inner.Name();
}

sealed class Cached(IRepository inner) : IRepository
{
    private readonly Dictionary<string, string> cache = new();

    public string Get(string key)
    {
        if (!cache.TryGetValue(key, out var value))
        {
            value = inner.Get(key);
            cache[key] = value;
        }
        return value;
    }

    public string Name() => inner.Name();
}
Output
log: get a
store: load a
value-a
log: get a
value-a
log: get b
store: load b
value-b
name: store
  • Verdict: idiom. The decorators implement IRepository and take the inner object through a primary constructor parameter.
  • System.IO.BufferedStream has this shape. It wraps another Stream and adds a buffer.
  • With a dependency injection container, the chain is often registered once, so that a class that asks for IRepository gets the outer decorator.
JavaScriptGitHub
class Store {
  get(key) {
    console.log(`store: load ${key}`);
    return `value-${key}`;
  }

  name() {
    return "store";
  }
}

class Logged {
  #inner;

  constructor(inner) {
    this.#inner = inner;
  }

  get(key) {
    console.log(`log: get ${key}`);
    return this.#inner.get(key);
  }

  name() {
    return this.#inner.name();
  }
}

class Cached {
  #inner;
  #cache = new Map();

  constructor(inner) {
    this.#inner = inner;
  }

  get(key) {
    if (!this.#cache.has(key)) {
      this.#cache.set(key, this.#inner.get(key));
    }
    return this.#cache.get(key);
  }

  name() {
    return this.#inner.name();
  }
}

const repo = new Logged(new Cached(new Store()));
for (const key of ["a", "a", "b"]) {
  console.log(repo.get(key));
}
console.log(`name: ${repo.name()}`);
Output
log: get a
store: load a
value-a
log: get a
value-a
log: get b
store: load b
value-b
name: store
  • Verdict: idiom. The interface is the set of method names that the client calls. Any object with get and name can be wrapped.
  • The private field #inner keeps the client from reaching past the decorator to the store.
  • The @decorator syntax of the TC39 proposal is a different construct. It runs a function on a class or a class element when the class is defined.
  • A Proxy object with a get trap can forward every property without writing each method. The trap then runs for every property access, which makes the code harder to follow.
TypeScriptGitHub
interface Repository {
  get(key: string): string;
  name(): string;
}

class Store implements Repository {
  get(key: string): string {
    console.log(`store: load ${key}`);
    return `value-${key}`;
  }

  name(): string {
    return "store";
  }
}

class Logged implements Repository {
  private readonly inner: Repository;

  constructor(inner: Repository) {
    this.inner = inner;
  }

  get(key: string): string {
    console.log(`log: get ${key}`);
    return this.inner.get(key);
  }

  name(): string {
    return this.inner.name();
  }
}

class Cached implements Repository {
  private readonly inner: Repository;
  private readonly cache = new Map<string, string>();

  constructor(inner: Repository) {
    this.inner = inner;
  }

  get(key: string): string {
    let value = this.cache.get(key);
    if (value === undefined) {
      value = this.inner.get(key);
      this.cache.set(key, value);
    }
    return value;
  }

  name(): string {
    return this.inner.name();
  }
}

const repo: Repository = new Logged(new Cached(new Store()));
for (const key of ["a", "a", "b"]) {
  console.log(repo.get(key));
}
console.log(`name: ${repo.name()}`);
Output
log: get a
store: load a
value-a
log: get a
value-a
log: get b
store: load b
value-b
name: store
  • Verdict: idiom. The decorators implement Repository and hold a Repository. If a decorator leaves out name, the compiler reports that the class does not implement the interface.
  • The types are structural, so implements is a check, not a requirement. An object literal with get and name is also a Repository.
  • The fields are assigned in the constructor body. Node runs this file by removing the types, and that mode does not accept parameter properties such as constructor(private inner: Repository).
  • TypeScript decorators (@name on a class or a member) are a different construct with the same name.
package main

import "fmt"

type Repository interface {
	Get(key string) string
	Name() string
}

type Store struct{}

func (Store) Get(key string) string {
	fmt.Println("store: load " + key)
	return "value-" + key
}

func (Store) Name() string { return "store" }

// Logged embeds the interface, so Name is promoted from the inner value.
type Logged struct {
	Repository
}

func (l Logged) Get(key string) string {
	fmt.Println("log: get " + key)
	return l.Repository.Get(key)
}

type Cached struct {
	Repository
	cache map[string]string
}

func NewCached(inner Repository) *Cached {
	return &Cached{Repository: inner, cache: map[string]string{}}
}

func (c *Cached) Get(key string) string {
	value, ok := c.cache[key]
	if !ok {
		value = c.Repository.Get(key)
		c.cache[key] = value
	}
	return value
}

func main() {
	var repo Repository = Logged{NewCached(Store{})}
	for _, key := range []string{"a", "a", "b"} {
		fmt.Println(repo.Get(key))
	}
	fmt.Println("name: " + repo.Name())
}
Output
log: get a
store: load a
value-a
log: get a
value-a
log: get b
store: load b
value-b
name: store
  • Verdict: idiom. A struct that embeds the interface gets the methods of the inner value as promoted methods. The decorator defines only Get, and Name forwards without code.
  • Cached has a pointer receiver because Get writes to the map. The chain holds a *Cached, which satisfies Repository.
  • For one operation, Go code uses a function that takes a handler and returns a handler. http.StripPrefix in net/http is an example.
  • If the embedded field is nil, a call to a promoted method panics. The constructor is the place to check it.
RustGitHub
use std::collections::HashMap;

trait Repository {
    fn get(&mut self, key: &str) -> String;
    fn name(&self) -> String;
}

struct Store;

impl Repository for Store {
    fn get(&mut self, key: &str) -> String {
        println!("store: load {key}");
        format!("value-{key}")
    }

    fn name(&self) -> String {
        "store".to_string()
    }
}

struct Logged<R: Repository> {
    inner: R,
}

impl<R: Repository> Repository for Logged<R> {
    fn get(&mut self, key: &str) -> String {
        println!("log: get {key}");
        self.inner.get(key)
    }

    fn name(&self) -> String {
        self.inner.name()
    }
}

struct Cached<R: Repository> {
    inner: R,
    cache: HashMap<String, String>,
}

impl<R: Repository> Cached<R> {
    fn new(inner: R) -> Self {
        Cached { inner, cache: HashMap::new() }
    }
}

impl<R: Repository> Repository for Cached<R> {
    fn get(&mut self, key: &str) -> String {
        if let Some(value) = self.cache.get(key) {
            return value.clone();
        }
        let value = self.inner.get(key);
        self.cache.insert(key.to_string(), value.clone());
        value
    }

    fn name(&self) -> String {
        self.inner.name()
    }
}

fn main() {
    let mut repo = Logged { inner: Cached::new(Store) };
    for key in ["a", "a", "b"] {
        println!("{}", repo.get(key));
    }
    println!("name: {}", repo.name());
}
Output
log: get a
store: load a
value-a
log: get a
value-a
log: get b
store: load b
value-b
name: store
  • Verdict: idiom. Each decorator is a generic struct that owns its inner value. The type of repo is Logged<Cached<Store>>, so the compiler knows the whole chain and can inline the calls.
  • get takes &mut self because the cache changes. A cache behind &self needs RefCell or a Mutex.
  • To choose the chain at run time, the decorators can hold a Box<dyn Repository> in place of the type parameter.
  • The standard library uses this shape. BufReader<R> wraps any R: Read, and the iterator adapters such as map and filter wrap an iterator and are iterators.
KotlinGitHub
interface Repository {
    fun get(key: String): String
    fun name(): String
}

class Store : Repository {
    override fun get(key: String): String {
        println("store: load $key")
        return "value-$key"
    }

    override fun name(): String = "store"
}

class Logged(private val inner: Repository) : Repository by inner {
    override fun get(key: String): String {
        println("log: get $key")
        return inner.get(key)
    }
}

class Cached(private val inner: Repository) : Repository by inner {
    private val cache = mutableMapOf<String, String>()

    override fun get(key: String): String = cache.getOrPut(key) { inner.get(key) }
}

fun main() {
    val repo: Repository = Logged(Cached(Store()))
    for (key in listOf("a", "a", "b")) {
        println(repo.get(key))
    }
    println("name: ${repo.name()}")
}
Output
log: get a
store: load a
value-a
log: get a
value-a
log: get b
store: load b
value-b
name: store
  • Verdict: native. Repository by inner makes the compiler write a forwarding method for each member of the interface. The decorators override only get, and name still works.
  • The delegation is to the object passed to the constructor, so the chain is still built at run time.
  • A member of the delegate that calls another member calls its own version, not the override in the decorator. The Kotlin documentation states this rule, and the node page shows the effect in Python.

Consequences

Design Patterns lists these benefits.1 Decorators are more flexible than static inheritance: a client can add and remove features at run time, and can use one feature twice. They avoid classes high up in a hierarchy that carry every feature. A program pays only for the features it uses.

The same chapter lists these costs.1 A decorator and its component are not the same object, so code that depends on object identity breaks. A design with many decorators has many small objects that look alike, and it is hard to learn and to debug.

Identity and type checks. The client holds the outer decorator. A check on the identity or the concrete type of the store fails on it:

class Store:
    def get(self, key):
        return f"value-{key}"


class Cached:
    def __init__(self, inner):
        self.inner = inner
        self.cache = {}

    def get(self, key):
        if key not in self.cache:
            self.cache[key] = self.inner.get(key)
        return self.cache[key]


store = Store()
repo = Cached(store)
print(repo.get("a"))
print(f"repo is store: {repo is store}")
print(f"isinstance(repo, Store): {isinstance(repo, Store)}")
Output
value-a
repo is store: False
isinstance(repo, Store): False

Code that uses a decorated object must use the interface only. A check such as isinstance(repo, Store) turns off the decorators without an error.

The order of the decorators changes the behaviour. Logged(Cached(store)) logs every call. Cached(Logged(store)) logs only the calls that miss the cache, because the cache answers the others before the logger sees them:

class Store:
    def get(self, key):
        return f"value-{key}"


class Logged:
    def __init__(self, inner):
        self.inner = inner

    def get(self, key):
        print(f"  log: get {key}")
        return self.inner.get(key)


class Cached:
    def __init__(self, inner):
        self.inner = inner
        self.cache = {}

    def get(self, key):
        if key not in self.cache:
            self.cache[key] = self.inner.get(key)
        return self.cache[key]


for name, repo in [("Logged(Cached(store))", Logged(Cached(Store()))),
                   ("Cached(Logged(store))", Cached(Logged(Store())))]:
    print(name)
    for key in ["a", "a", "b"]:
        repo.get(key)
Output
Logged(Cached(store))
  log: get a
  log: get a
  log: get b
Cached(Logged(store))
  log: get a
  log: get b

Neither order is wrong. Each order means something different, so the code that builds the chain must state the order on purpose.

Every operation must forward. A decorator that forgets an operation of the interface breaks the chain. A static type checker finds this in Java, C#, Go, Rust and TypeScript, because the decorator does not implement the interface. In Python the error comes at run time, on the first call:

This code raises AttributeError, on purpose.

class Store:
    def get(self, key):
        return f"value-{key}"

    def name(self):
        return "store"


class Logged:
    def __init__(self, inner):
        self.inner = inner

    def get(self, key):
        print(f"log: get {key}")
        return self.inner.get(key)


repo = Logged(Store())
print(repo.get("a"))
print(repo.name())

The run stops with AttributeError: 'Logged' object has no attribute 'name'. A large interface makes each decorator long, because each operation needs one line that forwards. Kotlin writes those lines for the programmer with by, and a Go struct that embeds the interface promotes the methods of the inner value.117 In Python, a __getattr__ method that returns getattr(self.inner, name) forwards every attribute that the decorator does not define.

Forwarding is not delegation. When a method of the inner object calls another of its own methods, it calls it on itself, not on the decorator. The decorator does not see that call. Here get_many is a method of the store, and the cache does not apply to the calls that it makes:

This code runs but gives a wrong answer on purpose.

class Store:
    def get(self, key):
        print(f"store: load {key}")
        return f"value-{key}"

    def get_many(self, keys):
        return [self.get(key) for key in keys]  # self is the store, not the decorator


class Cached:
    def __init__(self, inner):
        self.inner = inner
        self.cache = {}

    def get(self, key):
        if key not in self.cache:
            self.cache[key] = self.inner.get(key)
        return self.cache[key]

    def get_many(self, keys):
        return self.inner.get_many(keys)


repo = Cached(Store())
print(repo.get_many(["a", "a"]))
Output
store: load a
store: load a
['value-a', 'value-a']

The Kotlin documentation states the same rule for by. Members that the delegating class overrides are not called from the members of the delegate object. The delegate can call only its own implementations.11 The fix is to put the loop in the decorator, or in a function outside both, so that each get goes through the chain.

When not to use it

Do not use the pattern for a feature that every instance needs. Put it in the class, or in a base class. A decorator that is always present is a cost with no flexibility in return.

Do not use it when the interface is large and the decorator changes one operation. Each decorator must forward every other operation, and each forward is a place for a bug. A smaller interface, or a hook in the component, is often better. Design Patterns notes this: when the component class is heavy, Strategy is a better choice, because the decorators would be too costly.1

Do not use it when code depends on the concrete type or the identity of the object. Examples are equality on objects, a registry keyed by the object, and a check of the concrete type.

Do not build long chains in many places. Build the chain in one place, where the program wires its objects, so a reader can find the order.

Function decorators in Python. The @name syntax of Python applies a function to a function or a class at definition time. PEP 318 records that the name was criticized because it is not consistent with its use in the Design Patterns book. It adds that the name probably owes more to its use in the compiler area.12 A decorator function that returns a wrapper with the same signature is the pattern applied to one function. functools.wraps copies the name, the docstring and other attributes of the wrapped function to the wrapper, and sets __wrapped__:13

import functools


def logged(function):
    @functools.wraps(function)
    def wrapper(*args):
        print(f"log: {function.__name__}{args}")
        return function(*args)

    return wrapper


@logged
@functools.cache
def load(key):
    print(f"store: load {key}")
    return f"value-{key}"


print(load("a"))
print(load("a"))
print(load.__name__, load.__wrapped__.__wrapped__.__name__)
Output
log: load('a',)
store: load a
value-a
log: load('a',)
value-a
load load

Decorators in JavaScript and TypeScript. The TC39 decorators proposal and the TypeScript decorators are syntax. They run a function on a class, a method or a field when the class is defined.1516 Like the Python syntax, they can implement the pattern, but they are a language feature, not the pattern itself.

Adapter. An adapter changes the interface of an object. A decorator keeps the interface and changes the behaviour.1 The Adapter pattern page shows the contrast. Rust calls its iterator wrappers, such as map and filter, adapters, and its documentation describes them as a form of the adapter pattern.9 By structure they are closer to decorators, because each one takes an iterator and returns an iterator.

Composite. Design Patterns describes a decorator as a degenerate composite with one component. A decorator adds responsibilities, and a composite aggregates objects.1

Strategy. Design Patterns contrasts the two: a decorator changes the skin of an object, and a strategy changes its guts.1 A decorator works from the outside, and the component does not know about it. A strategy is a part that the component knows and calls.

Proxy. A proxy has the same structure, an object with the same interface that forwards. Its purpose is to control access to the object, for example to create it late or to reach it over a network. It does not add features that a client chooses.19

Middleware. A web server can pass a request through a list of handlers, each of which can act and then call the next. That list is a chain of decorators of one operation.6

Known uses

  • OpenJDK: FilterInputStream.java at jdk-25+36 holds the wrapped stream in the field in, sets it in the constructor, and forwards read() to in.read(). BufferedInputStream, DataInputStream and the other filter streams extend it.17
  • Go: StripPrefix in server.go at go1.27.3 returns a HandlerFunc. It removes a prefix from the path of a copy of the request and calls the wrapped handler.18

References

  1. Gamma, Helm, Johnson and Vlissides, Design Patterns, Elements of Reusable Object-Oriented Software, Addison-Wesley, 1994, Chapter 4, Decorator (Intent, Also Known As, Motivation, Participants, Consequences, Implementation, Known Uses, Related Patterns)
  2. Joshua Kerievsky, Refactoring to Patterns, Addison-Wesley, 2004, Chapter 7, Simplification, Move Embellishment to Decorator (problem and solution)
  3. Java SE 25 API, java.io.FilterInputStream, class description
  4. Java SE 25 API, java.io.BufferedInputStream, class description
  5. The Python Standard Library, io, Python 3.14, io.BufferedReader
  6. Go standard library, package net/http, func StripPrefix
  7. The Go Programming Language Specification, Struct types (embedded fields and promoted methods)
  8. Rust standard library, std::io::BufReader, struct description
  9. Rust standard library, module std::iter, Adapters
  10. .NET API reference, System.IO.BufferedStream, class description
  11. Kotlin documentation, Delegation, Implementation by delegation; Overriding a member of an interface implemented by delegation
  12. PEP 318, Decorators for Functions and Methods, On the name 'Decorator'
  13. The Python Standard Library, functools, Python 3.14, functools.update_wrapper and functools.wraps
  14. The Python Standard Library, functools, Python 3.14, functools.cache and functools.lru_cache
  15. TC39 proposal, Decorators, README, Detailed design
  16. TypeScript Handbook, Decorators, Decorators (experimental decorators and the compiler option)
  17. OpenJDK jdk-25+36 source, java/io/FilterInputStream.java, the field in, the constructor and read, lines 45 to 72
  18. Go go1.27.3 source, src/net/http/server.go, StripPrefix, lines 2406 to 2425
  19. Gamma, Helm, Johnson and Vlissides, Design Patterns, Elements of Reusable Object-Oriented Software, Addison-Wesley, 1994, Chapter 4, Proxy (Intent, Applicability, Related Patterns)

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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/E4GM49/text.yaml