Polski

Article · Decorator · Proxy

Decorator – adding behaviour layer by layer

Decorator wraps an object in another object with the same interface and adds behaviour before or after the call. An example of caching, retries and logging for an exchange rate provider in C#, TypeScript, Java, Go and Python.

By · · 11 min read

A working class needs a cache. Then retries on network errors. Then logging, timing, rate limiting… Decorator lets you add such behaviour without changing the original class and without creating a subclass for every combination: each behaviour is a separate "layer" that wraps the object and has the same interface.

The problem: a rate provider overgrown with ifs

The pierogi shop accepts payments in euro, so it needs the current exchange rate from a bank API. The API is sometimes slow and occasionally times out, and querying it for every basket is expensive. The first version of the class grew with every request:

bank-rates.ts
class BankRates {
  async getRate(currency: string): Promise<number> {
    if (this.cache.has(currency)) return this.cache.get(currency)!; // caching
    for (let i = 0; i < 3; i++) {                                    // retrying
      try {
        console.log(`asking for ${currency}`);                       // logging
        const rate = await this.http.get(`/rates/${currency}`);      // the actual job
        this.cache.set(currency, rate);
        return rate;
      } catch { /* retry */ }
    }
    throw new Error("bank unavailable");
  }
}

One method does four things. Tests cannot switch the cache off, the admin panel wants a rate without caching, and the nightly job wants one without logging. Subclasses CachedBankRates, CachedLoggedBankRates, RetryingCachedBankRates quickly turn into a multiplication table.

The solution: every responsibility is a separate layer

We keep a class that does only one thing – it asks the bank API. Every additional behaviour is a separate class implementing the same RateProvider interface and holding a reference to an "inner" provider. CachedRates checks the cache and, if it finds nothing, asks the inner object. RetryingRates retries the inner object's call. The client receives the outermost layer and does not know how many there are.

Diagram: Decorator layers around the real provider
Diagram: Structure: decorators implement the same interface and wrap a component
RoleIn the exampleResponsibility
ComponentRateProviderthe common interface of the object and its decorators
Concrete componentFlakyBankApithe actual work – asking the bank
Concrete decoratorRetryingRates, CachedRates, LoggingRatesone extra behaviour + delegation to inner
Clientthe basketuses the interface, unaware of the layers

The GoF version also has an abstract Decorator class holding the component reference, from which concrete decorators inherit. Modern code often skips it – each decorator simply takes inner in its constructor.

Implementation in five languages

Our bank API deliberately times out on every other call. Look at the output: the first request succeeds thanks to the retry, and the second never reaches the bank, because the cache serves it.

IRateProvider decorators

Rates.cs
IRateProvider rates = new LoggingRates(new CachedRates(new RetryingRates(new FlakyBankApi(), attempts: 3)));
Console.WriteLine(rates.GetRate("EUR"));
Console.WriteLine(rates.GetRate("EUR")); // served from the cache, no API call

public interface IRateProvider
{
    decimal GetRate(string currency);
}

// The real component: a remote API that times out on every other call.
public sealed class FlakyBankApi : IRateProvider
{
    private int _calls;

    public decimal GetRate(string currency) =>
        ++_calls % 2 == 1 ? throw new HttpRequestException("timeout") : 4.27m;
}

// Each decorator implements the same interface and wraps another provider.
public sealed class RetryingRates(IRateProvider inner, int attempts) : IRateProvider
{
    public decimal GetRate(string currency)
    {
        for (var attempt = 1; ; attempt++)
        {
            try { return inner.GetRate(currency); }
            catch (HttpRequestException) when (attempt < attempts) { /* try again */ }
        }
    }
}

public sealed class CachedRates(IRateProvider inner) : IRateProvider
{
    private readonly Dictionary<string, decimal> _cache = new();

    public decimal GetRate(string currency) =>
        _cache.TryGetValue(currency, out var rate) ? rate : _cache[currency] = inner.GetRate(currency);
}

public sealed class LoggingRates(IRateProvider inner) : IRateProvider
{
    public decimal GetRate(string currency)
    {
        Console.WriteLine($"[log] asking for {currency}");
        return inner.GetRate(currency);
    }
}
rates.ts
interface RateProvider {
  getRate(currency: string): Promise<number>;
}

// The real component: a remote API that times out on every other call.
class FlakyBankApi implements RateProvider {
  private calls = 0;
  async getRate(currency: string): Promise<number> {
    if (++this.calls % 2 === 1) throw new Error("timeout");
    return 4.27;
  }
}

// Each decorator implements the same interface and wraps another provider.
class RetryingRates implements RateProvider {
  constructor(private readonly inner: RateProvider, private readonly attempts: number) {}

  async getRate(currency: string): Promise<number> {
    for (let attempt = 1; ; attempt++) {
      try {
        return await this.inner.getRate(currency);
      } catch (err) {
        if (attempt >= this.attempts) throw err;
      }
    }
  }
}

class CachedRates implements RateProvider {
  private readonly cache = new Map<string, number>();
  constructor(private readonly inner: RateProvider) {}

  async getRate(currency: string): Promise<number> {
    const cached = this.cache.get(currency);
    if (cached !== undefined) return cached;
    const rate = await this.inner.getRate(currency);
    this.cache.set(currency, rate);
    return rate;
  }
}

class LoggingRates implements RateProvider {
  constructor(private readonly inner: RateProvider) {}

  getRate(currency: string): Promise<number> {
    console.log(`[log] asking for ${currency}`);
    return this.inner.getRate(currency);
  }
}

const rates: RateProvider = new LoggingRates(new CachedRates(new RetryingRates(new FlakyBankApi(), 3)));
rates.getRate("EUR").then(console.log).then(() => rates.getRate("EUR")).then(console.log);
Rates.java
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

interface RateProvider {
    BigDecimal getRate(String currency);
}

// The real component: a remote API that times out on every other call.
class FlakyBankApi implements RateProvider {
    private int calls;
    public BigDecimal getRate(String currency) {
        if (++calls % 2 == 1) throw new IllegalStateException("timeout");
        return new BigDecimal("4.27");
    }
}

// Each decorator implements the same interface and wraps another provider.
record RetryingRates(RateProvider inner, int attempts) implements RateProvider {
    public BigDecimal getRate(String currency) {
        for (int attempt = 1; ; attempt++) {
            try {
                return inner.getRate(currency);
            } catch (IllegalStateException e) {
                if (attempt >= attempts) throw e;
            }
        }
    }
}

class CachedRates implements RateProvider {
    private final Map<String, BigDecimal> cache = new HashMap<>();
    private final RateProvider inner;
    CachedRates(RateProvider inner) { this.inner = inner; }
    public BigDecimal getRate(String currency) { return cache.computeIfAbsent(currency, inner::getRate); }
}

record LoggingRates(RateProvider inner) implements RateProvider {
    public BigDecimal getRate(String currency) {
        System.out.println("[log] asking for " + currency);
        return inner.getRate(currency);
    }
}

public class Rates {
    public static void main(String[] args) {
        RateProvider rates = new LoggingRates(new CachedRates(new RetryingRates(new FlakyBankApi(), 3)));
        System.out.println(rates.getRate("EUR"));
        System.out.println(rates.getRate("EUR")); // served from the cache
    }
}
rates.go
package main

import (
	"errors"
	"fmt"
)

type RateProvider interface {
	Rate(currency string) (float64, error)
}

// FlakyBankAPI is the real component: it times out on every other call.
type FlakyBankAPI struct{ calls int }

func (a *FlakyBankAPI) Rate(string) (float64, error) {
	a.calls++
	if a.calls%2 == 1 {
		return 0, errors.New("timeout")
	}
	return 4.27, nil
}

// Each decorator satisfies RateProvider and wraps another one.
type Retrying struct {
	Inner    RateProvider
	Attempts int
}

func (r Retrying) Rate(currency string) (rate float64, err error) {
	for i := 0; i < r.Attempts; i++ {
		if rate, err = r.Inner.Rate(currency); err == nil {
			return rate, nil
		}
	}
	return 0, err
}

type Cached struct {
	Inner RateProvider
	cache map[string]float64
}

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

func (c *Cached) Rate(currency string) (float64, error) {
	if rate, ok := c.cache[currency]; ok {
		return rate, nil
	}
	rate, err := c.Inner.Rate(currency)
	if err == nil {
		c.cache[currency] = rate
	}
	return rate, err
}

func main() {
	var rates RateProvider = NewCached(Retrying{Inner: &FlakyBankAPI{}, Attempts: 3})
	fmt.Println(rates.Rate("EUR"))
	fmt.Println(rates.Rate("EUR")) // served from the cache
}
rates.py
from typing import Protocol


class RateProvider(Protocol):
    def get_rate(self, currency: str) -> float: ...


class FlakyBankApi:
    """The real component: a remote API that times out on every other call."""

    def __init__(self) -> None:
        self._calls = 0

    def get_rate(self, currency: str) -> float:
        self._calls += 1
        if self._calls % 2 == 1:
            raise TimeoutError("timeout")
        return 4.27


# Each decorator implements the same protocol and wraps another provider.
class RetryingRates:
    def __init__(self, inner: RateProvider, attempts: int) -> None:
        self._inner = inner
        self._attempts = attempts

    def get_rate(self, currency: str) -> float:
        for attempt in range(1, self._attempts + 1):
            try:
                return self._inner.get_rate(currency)
            except TimeoutError:
                if attempt == self._attempts:
                    raise
        raise AssertionError("unreachable")


class CachedRates:
    def __init__(self, inner: RateProvider) -> None:
        self._inner = inner
        self._cache: dict[str, float] = {}

    def get_rate(self, currency: str) -> float:
        if currency not in self._cache:
            self._cache[currency] = self._inner.get_rate(currency)
        return self._cache[currency]


class LoggingRates:
    def __init__(self, inner: RateProvider) -> None:
        self._inner = inner

    def get_rate(self, currency: str) -> float:
        print(f"[log] asking for {currency}")
        return self._inner.get_rate(currency)


if __name__ == "__main__":
    rates: RateProvider = LoggingRates(CachedRates(RetryingRates(FlakyBankApi(), attempts=3)))
    print(rates.get_rate("EUR"))
    print(rates.get_rate("EUR"))  # served from the cache

The rest of this article is for members

Create a free account or sign in to read it all. Still ahead:

  • Step by step
  • When to use it and when not to
  • Decorator vs the @decorator syntax
  • Related patterns
  • In practice
  • Quick check
  • Summary

Create a free account · Sign in