English

Artykuł · Dekorator · Pełnomocnik

Dekorator (Decorator) – dokładanie zachowania warstwa po warstwie

Dekorator owija obiekt innym obiektem o tym samym interfejsie i dodaje zachowanie przed wywołaniem lub po nim. Przykład pamięci podręcznej, ponowień i logowania dla dostawcy kursów walut w C#, TypeScript, Javie, Go i Pythonie.

Autor · · 11 min czytania

Do działającej klasy trzeba dodać pamięć podręczną. Potem ponawianie przy błędach sieci. Potem logowanie, pomiar czasu, limit zapytań… Dekorator (ang. Decorator) pozwala dokładać takie zachowania bez zmieniania oryginalnej klasy i bez tworzenia podklas dla każdej kombinacji: każde zachowanie to osobna „warstwa”, która owija obiekt i ma ten sam interfejs co on.

Problem: dostawca kursów, który obrasta w ifs

Sklep pierogarni przyjmuje płatności w euro, więc potrzebuje aktualnego kursu z API banku. API bywa wolne i czasem zwraca błąd przekroczenia czasu, a odpytywanie go przy każdym koszyku jest drogie. Pierwsza wersja klasy rosła z każdą prośbą:

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");
  }
}

Jedna metoda robi cztery rzeczy. W testach nie da się wyłączyć pamięci podręcznej, w panelu administracyjnym chcemy kursu bez cache, a w zadaniu nocnym – bez logowania. Podklasy CachedBankRates, CachedLoggedBankRates, RetryingCachedBankRates szybko zamieniają się w tabliczkę mnożenia.

Rozwiązanie: każda odpowiedzialność to osobna warstwa

Zostawiamy klasę, która robi tylko jedno – pyta API banku. Każde dodatkowe zachowanie to osobna klasa implementująca ten sam interfejs RateProvider i trzymająca referencję do „wewnętrznego” dostawcy. CachedRates sprawdza pamięć podręczną, a gdy nic nie znajdzie, pyta obiekt wewnętrzny. RetryingRates ponawia wywołanie obiektu wewnętrznego. Klient dostaje najbardziej zewnętrzną warstwę i nie wie, ile ich jest.

Diagram: Warstwy dekoratorów wokół prawdziwego dostawcy
Diagram: Struktura: dekoratory implementują ten sam interfejs i owijają komponent
RolaW przykładzieOdpowiedzialność
Komponent (Component)RateProviderwspólny interfejs obiektu i dekoratorów
Komponent konkretnyFlakyBankApiwłaściwa praca – zapytanie do banku
Dekorator konkretnyRetryingRates, CachedRates, LoggingRatesjedno dodatkowe zachowanie + delegacja do inner
Klientkoszykużywa interfejsu, nie wie o warstwach

W wersji GoF jest jeszcze abstrakcyjna klasa Decorator przechowująca referencję do komponentu, po której dziedziczą dekoratory konkretne. W nowoczesnym kodzie często się ją pomija – każdy dekorator po prostu przyjmuje inner w konstruktorze.

Implementacja w pięciu językach

Nasze API banku celowo przekracza czas przy co drugim wywołaniu. Zwróć uwagę na wynik: pierwsze zapytanie przechodzi dzięki ponowieniu, a drugie w ogóle nie dociera do banku, bo obsługuje je pamięć podręczna.

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

Dalsza część artykułu dla zalogowanych

Załóż darmowe konto albo zaloguj się, aby przeczytać całość. W dalszej części:

  • Krok po kroku
  • Kiedy stosować, a kiedy nie
  • Dekorator a składnia @decorator
  • Powiązania z innymi wzorcami
  • W praktyce
  • Szybki test
  • Podsumowanie

Załóż darmowe konto · Zaloguj się