{"id":"6b08bd3280884893657cc938","slug":"decorator","title":"Decorator – adding behaviour layer by layer","summary":"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.","servedLang":"en","availableLangs":["pl","en"],"topics":["decorator","proxy","chain-of-responsibility","composite"],"techs":["dotnet","typescript","java","go","python"],"tags":["gof","structural","decorator","middleware","cross-cutting-concerns"],"level":"intermediate","kind":"article","access":"members","status":"published","cover":null,"author":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","community":false},"readingMinutes":11,"stats":{"views":3,"likes":0,"bookmarks":0,"comments":0},"publishedAt":"2026-11-26T23:13:54.428Z","updatedAt":"2026-11-27T13:08:21.545Z","requestedLang":"en","theme":{"hero":"classic","heroMedia":null,"accent":"indigo","background":"dots","weaveResources":true,"toc":"right"},"seoDescription":"The Decorator design pattern – the subclass explosion problem, wrapping objects, the order of layers, diagrams, code in C#, TypeScript, Java, Go and Python, Scrutor, java.io streams, Go middleware, Python and TypeScript decorators.","wordCount":2170,"doc":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"A working class needs a cache. Then retries on network errors. Then logging, timing, rate limiting… "},{"type":"text","text":"Decorator","marks":[{"type":"bold"}]},{"type":"text","text":" 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."}]},{"type":"callout","attrs":{"variant":"info","title":"In short"},"content":[{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"A decorator implements the same interface as the object it wraps and delegates calls to it."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Before or after delegating, it adds its own behaviour: caching, retries, logging, authorisation."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Layers can be combined freely at runtime – the order matters."}]}]}]}]},{"type":"heading","attrs":{"level":2,"id":"the-problem-a-rate-provider-overgrown-with-ifs"},"content":[{"type":"text","text":"The problem: a rate provider overgrown with ifs"}]},{"type":"paragraph","content":[{"type":"text","text":"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:"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"bank-rates.ts"},"content":[{"type":"text","text":"class BankRates {\n  async getRate(currency: string): Promise<number> {\n    if (this.cache.has(currency)) return this.cache.get(currency)!; // caching\n    for (let i = 0; i < 3; i++) {                                    // retrying\n      try {\n        console.log(`asking for ${currency}`);                       // logging\n        const rate = await this.http.get(`/rates/${currency}`);      // the actual job\n        this.cache.set(currency, rate);\n        return rate;\n      } catch { /* retry */ }\n    }\n    throw new Error(\"bank unavailable\");\n  }\n}"}]},{"type":"paragraph","content":[{"type":"text","text":"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 "},{"type":"text","text":"CachedBankRates","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"CachedLoggedBankRates","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"RetryingCachedBankRates","marks":[{"type":"code"}]},{"type":"text","text":" quickly turn into a multiplication table."}]},{"type":"heading","attrs":{"level":2,"id":"the-solution-every-responsibility-is-a-separate-layer"},"content":[{"type":"text","text":"The solution: every responsibility is a separate layer"}]},{"type":"paragraph","content":[{"type":"text","text":"We keep a class that does only one thing – it asks the bank API. Every additional behaviour is a separate class implementing the same "},{"type":"text","text":"RateProvider","marks":[{"type":"code"}]},{"type":"text","text":" interface and holding a reference to an \"inner\" provider. "},{"type":"text","text":"CachedRates","marks":[{"type":"code"}]},{"type":"text","text":" checks the cache and, if it finds nothing, asks the inner object. "},{"type":"text","text":"RetryingRates","marks":[{"type":"code"}]},{"type":"text","text":" retries the inner object's call. The client receives the outermost layer and does not know how many there are."}]},{"type":"diagram","attrs":{"kind":"mermaid","code":"flowchart LR\n  K[\"Basket\"] --> L[\"LoggingRates\"]\n  L --> C[\"CachedRates\"]\n  C -->|\"cache miss\"| R[\"RetryingRates\"]\n  R -->|\"up to 3 attempts\"| B[(\"FlakyBankApi\")]","caption":"Decorator layers around the real provider"}},{"type":"diagram","attrs":{"kind":"mermaid","code":"classDiagram\n  direction LR\n  class RateProvider {\n    <<interface>>\n    +getRate(currency) decimal\n  }\n  class FlakyBankApi {\n    +getRate(currency) decimal\n  }\n  class RetryingRates {\n    -inner RateProvider\n    -attempts int\n  }\n  class CachedRates {\n    -inner RateProvider\n    -cache Map\n  }\n  class LoggingRates {\n    -inner RateProvider\n  }\n  RateProvider <|.. FlakyBankApi\n  RateProvider <|.. RetryingRates\n  RateProvider <|.. CachedRates\n  RateProvider <|.. LoggingRates\n  RetryingRates o-- RateProvider : inner\n  CachedRates o-- RateProvider : inner\n  LoggingRates o-- RateProvider : inner","caption":"Structure: decorators implement the same interface and wrap a component"}},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Role"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"In the example"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Responsibility"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Component"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"RateProvider","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"the common interface of the object and its decorators"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Concrete component"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"FlakyBankApi","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"the actual work – asking the bank"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Concrete decorator"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"RetryingRates","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"CachedRates","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"LoggingRates","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"one extra behaviour + delegation to "},{"type":"text","text":"inner","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Client"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"the basket"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"uses the interface, unaware of the layers"}]}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"The GoF version also has an abstract "},{"type":"text","text":"Decorator","marks":[{"type":"code"}]},{"type":"text","text":" class holding the component reference, from which concrete decorators inherit. Modern code often skips it – each decorator simply takes "},{"type":"text","text":"inner","marks":[{"type":"code"}]},{"type":"text","text":" in its constructor."}]},{"type":"heading","attrs":{"level":2,"id":"implementation-in-five-languages"},"content":[{"type":"text","text":"Implementation in five languages"}]},{"type":"paragraph","content":[{"type":"text","text":"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."}]},{"type":"codeGroup","attrs":{"title":"IRateProvider decorators"},"content":[{"type":"codeBlock","attrs":{"language":"csharp","filename":"Rates.cs"},"content":[{"type":"text","text":"IRateProvider rates = new LoggingRates(new CachedRates(new RetryingRates(new FlakyBankApi(), attempts: 3)));\nConsole.WriteLine(rates.GetRate(\"EUR\"));\nConsole.WriteLine(rates.GetRate(\"EUR\")); // served from the cache, no API call\n\npublic interface IRateProvider\n{\n    decimal GetRate(string currency);\n}\n\n// The real component: a remote API that times out on every other call.\npublic sealed class FlakyBankApi : IRateProvider\n{\n    private int _calls;\n\n    public decimal GetRate(string currency) =>\n        ++_calls % 2 == 1 ? throw new HttpRequestException(\"timeout\") : 4.27m;\n}\n\n// Each decorator implements the same interface and wraps another provider.\npublic sealed class RetryingRates(IRateProvider inner, int attempts) : IRateProvider\n{\n    public decimal GetRate(string currency)\n    {\n        for (var attempt = 1; ; attempt++)\n        {\n            try { return inner.GetRate(currency); }\n            catch (HttpRequestException) when (attempt < attempts) { /* try again */ }\n        }\n    }\n}\n\npublic sealed class CachedRates(IRateProvider inner) : IRateProvider\n{\n    private readonly Dictionary<string, decimal> _cache = new();\n\n    public decimal GetRate(string currency) =>\n        _cache.TryGetValue(currency, out var rate) ? rate : _cache[currency] = inner.GetRate(currency);\n}\n\npublic sealed class LoggingRates(IRateProvider inner) : IRateProvider\n{\n    public decimal GetRate(string currency)\n    {\n        Console.WriteLine($\"[log] asking for {currency}\");\n        return inner.GetRate(currency);\n    }\n}"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"rates.ts"},"content":[{"type":"text","text":"interface RateProvider {\n  getRate(currency: string): Promise<number>;\n}\n\n// The real component: a remote API that times out on every other call.\nclass FlakyBankApi implements RateProvider {\n  private calls = 0;\n  async getRate(currency: string): Promise<number> {\n    if (++this.calls % 2 === 1) throw new Error(\"timeout\");\n    return 4.27;\n  }\n}\n\n// Each decorator implements the same interface and wraps another provider.\nclass RetryingRates implements RateProvider {\n  constructor(private readonly inner: RateProvider, private readonly attempts: number) {}\n\n  async getRate(currency: string): Promise<number> {\n    for (let attempt = 1; ; attempt++) {\n      try {\n        return await this.inner.getRate(currency);\n      } catch (err) {\n        if (attempt >= this.attempts) throw err;\n      }\n    }\n  }\n}\n\nclass CachedRates implements RateProvider {\n  private readonly cache = new Map<string, number>();\n  constructor(private readonly inner: RateProvider) {}\n\n  async getRate(currency: string): Promise<number> {\n    const cached = this.cache.get(currency);\n    if (cached !== undefined) return cached;\n    const rate = await this.inner.getRate(currency);\n    this.cache.set(currency, rate);\n    return rate;\n  }\n}\n\nclass LoggingRates implements RateProvider {\n  constructor(private readonly inner: RateProvider) {}\n\n  getRate(currency: string): Promise<number> {\n    console.log(`[log] asking for ${currency}`);\n    return this.inner.getRate(currency);\n  }\n}\n\nconst rates: RateProvider = new LoggingRates(new CachedRates(new RetryingRates(new FlakyBankApi(), 3)));\nrates.getRate(\"EUR\").then(console.log).then(() => rates.getRate(\"EUR\")).then(console.log);"}]},{"type":"codeBlock","attrs":{"language":"java","filename":"Rates.java"},"content":[{"type":"text","text":"import java.math.BigDecimal;\nimport java.util.HashMap;\nimport java.util.Map;\n\ninterface RateProvider {\n    BigDecimal getRate(String currency);\n}\n\n// The real component: a remote API that times out on every other call.\nclass FlakyBankApi implements RateProvider {\n    private int calls;\n    public BigDecimal getRate(String currency) {\n        if (++calls % 2 == 1) throw new IllegalStateException(\"timeout\");\n        return new BigDecimal(\"4.27\");\n    }\n}\n\n// Each decorator implements the same interface and wraps another provider.\nrecord RetryingRates(RateProvider inner, int attempts) implements RateProvider {\n    public BigDecimal getRate(String currency) {\n        for (int attempt = 1; ; attempt++) {\n            try {\n                return inner.getRate(currency);\n            } catch (IllegalStateException e) {\n                if (attempt >= attempts) throw e;\n            }\n        }\n    }\n}\n\nclass CachedRates implements RateProvider {\n    private final Map<String, BigDecimal> cache = new HashMap<>();\n    private final RateProvider inner;\n    CachedRates(RateProvider inner) { this.inner = inner; }\n    public BigDecimal getRate(String currency) { return cache.computeIfAbsent(currency, inner::getRate); }\n}\n\nrecord LoggingRates(RateProvider inner) implements RateProvider {\n    public BigDecimal getRate(String currency) {\n        System.out.println(\"[log] asking for \" + currency);\n        return inner.getRate(currency);\n    }\n}\n\npublic class Rates {\n    public static void main(String[] args) {\n        RateProvider rates = new LoggingRates(new CachedRates(new RetryingRates(new FlakyBankApi(), 3)));\n        System.out.println(rates.getRate(\"EUR\"));\n        System.out.println(rates.getRate(\"EUR\")); // served from the cache\n    }\n}"}]},{"type":"codeBlock","attrs":{"language":"go","filename":"rates.go"},"content":[{"type":"text","text":"package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\ntype RateProvider interface {\n\tRate(currency string) (float64, error)\n}\n\n// FlakyBankAPI is the real component: it times out on every other call.\ntype FlakyBankAPI struct{ calls int }\n\nfunc (a *FlakyBankAPI) Rate(string) (float64, error) {\n\ta.calls++\n\tif a.calls%2 == 1 {\n\t\treturn 0, errors.New(\"timeout\")\n\t}\n\treturn 4.27, nil\n}\n\n// Each decorator satisfies RateProvider and wraps another one.\ntype Retrying struct {\n\tInner    RateProvider\n\tAttempts int\n}\n\nfunc (r Retrying) Rate(currency string) (rate float64, err error) {\n\tfor i := 0; i < r.Attempts; i++ {\n\t\tif rate, err = r.Inner.Rate(currency); err == nil {\n\t\t\treturn rate, nil\n\t\t}\n\t}\n\treturn 0, err\n}\n\ntype Cached struct {\n\tInner RateProvider\n\tcache map[string]float64\n}\n\nfunc NewCached(inner RateProvider) *Cached {\n\treturn &Cached{Inner: inner, cache: map[string]float64{}}\n}\n\nfunc (c *Cached) Rate(currency string) (float64, error) {\n\tif rate, ok := c.cache[currency]; ok {\n\t\treturn rate, nil\n\t}\n\trate, err := c.Inner.Rate(currency)\n\tif err == nil {\n\t\tc.cache[currency] = rate\n\t}\n\treturn rate, err\n}\n\nfunc main() {\n\tvar rates RateProvider = NewCached(Retrying{Inner: &FlakyBankAPI{}, Attempts: 3})\n\tfmt.Println(rates.Rate(\"EUR\"))\n\tfmt.Println(rates.Rate(\"EUR\")) // served from the cache\n}"}]},{"type":"codeBlock","attrs":{"language":"python","filename":"rates.py"},"content":[{"type":"text","text":"from typing import Protocol\n\n\nclass RateProvider(Protocol):\n    def get_rate(self, currency: str) -> float: ...\n\n\nclass FlakyBankApi:\n    \"\"\"The real component: a remote API that times out on every other call.\"\"\"\n\n    def __init__(self) -> None:\n        self._calls = 0\n\n    def get_rate(self, currency: str) -> float:\n        self._calls += 1\n        if self._calls % 2 == 1:\n            raise TimeoutError(\"timeout\")\n        return 4.27\n\n\n# Each decorator implements the same protocol and wraps another provider.\nclass RetryingRates:\n    def __init__(self, inner: RateProvider, attempts: int) -> None:\n        self._inner = inner\n        self._attempts = attempts\n\n    def get_rate(self, currency: str) -> float:\n        for attempt in range(1, self._attempts + 1):\n            try:\n                return self._inner.get_rate(currency)\n            except TimeoutError:\n                if attempt == self._attempts:\n                    raise\n        raise AssertionError(\"unreachable\")\n\n\nclass CachedRates:\n    def __init__(self, inner: RateProvider) -> None:\n        self._inner = inner\n        self._cache: dict[str, float] = {}\n\n    def get_rate(self, currency: str) -> float:\n        if currency not in self._cache:\n            self._cache[currency] = self._inner.get_rate(currency)\n        return self._cache[currency]\n\n\nclass LoggingRates:\n    def __init__(self, inner: RateProvider) -> None:\n        self._inner = inner\n\n    def get_rate(self, currency: str) -> float:\n        print(f\"[log] asking for {currency}\")\n        return self._inner.get_rate(currency)\n\n\nif __name__ == \"__main__\":\n    rates: RateProvider = LoggingRates(CachedRates(RetryingRates(FlakyBankApi(), attempts=3)))\n    print(rates.get_rate(\"EUR\"))\n    print(rates.get_rate(\"EUR\"))  # served from the cache"}]}]}]},"toc":[{"id":"the-problem-a-rate-provider-overgrown-with-ifs","text":"The problem: a rate provider overgrown with ifs","level":2,"locked":false},{"id":"the-solution-every-responsibility-is-a-separate-layer","text":"The solution: every responsibility is a separate layer","level":2,"locked":false},{"id":"implementation-in-five-languages","text":"Implementation in five languages","level":2,"locked":false},{"id":"step-by-step","text":"Step by step","level":2,"locked":true},{"id":"when-to-use-it-and-when-not-to","text":"When to use it and when not to","level":2,"locked":true},{"id":"decorator-vs-the-decorator-syntax","text":"Decorator vs the @decorator syntax","level":2,"locked":true},{"id":"related-patterns","text":"Related patterns","level":2,"locked":true},{"id":"in-practice","text":"In practice","level":2,"locked":true},{"id":"quick-check","text":"Quick check","level":2,"locked":true},{"id":"summary","text":"Summary","level":2,"locked":true}],"locked":true,"paywall":null,"previewRatio":0.3,"totalBlocks":37,"visibleBlocks":15,"resources":[{"id":"6b0857a53c96f2d34d0b321c","type":"video","provider":"youtube","url":"https://www.youtube.com/watch?v=GCraGHx6gso","embedUrl":"https://www.youtube-nocookie.com/embed/GCraGHx6gso","title":"Decorator Pattern – Design Patterns (ep 3)","description":"","author":"Christopher Okhravi","thumbnailUrl":"https://i.ytimg.com/vi/GCraGHx6gso/hqdefault.jpg","durationSec":null,"lang":"en","topics":["decorator"],"techs":["general"],"tags":[],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"seed","publishedAt":null,"popularity":0,"verifiedAt":"2026-11-26T00:00:00.000Z","curated":true,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:37.563Z","updatedAt":"2026-11-26T16:00:37.563Z"},{"id":"6b0857c73c96f2d34d0b4929","type":"video","provider":"youtube","url":"https://www.youtube.com/watch?v=gsluG8NdCfw","embedUrl":"https://www.youtube-nocookie.com/embed/gsluG8NdCfw","title":"Building Your Own CQRS Pipeline With Decorators (Dropped MediatR!)","description":"Get the free Clean Architecture template: https://dub.sh/ca-template Want to master Clean Architecture? Go here: https://bit.ly/3PupkOJ Want to unlock Modular Monoliths? Go here: https://bit.ly/3SXlzSt So… you’ve removed MediatR. But how do you replace pipeline behaviors like logging and…","author":"Milan Jovanović","thumbnailUrl":"https://i.ytimg.com/vi/gsluG8NdCfw/hqdefault.jpg","durationSec":null,"lang":"en","topics":["decorator","modular-monolith","clean-architecture","cqrs"],"techs":["dotnet"],"tags":["design-patterns","software-architecture"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"youtube-rss","publishedAt":"2025-05-16T11:01:28.000Z","popularity":65,"verifiedAt":"2026-11-26T10:54:01.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:10.095Z","updatedAt":"2026-11-26T16:01:10.095Z"},{"id":"6b0857aa3c96f2d34d0b3268","type":"package","provider":"nuget","url":"https://www.nuget.org/packages/Scrutor","embedUrl":null,"title":"Scrutor","description":"Assembly scanning and decoration for Microsoft.Extensions.DependencyInjection (services.Decorate).","author":"","thumbnailUrl":null,"durationSec":null,"lang":"en","topics":["decorator","solid"],"techs":["dotnet"],"tags":["dependency-injection"],"price":"free","featured":false,"featuredOrder":23,"packageName":"Scrutor","source":"seed","publishedAt":null,"popularity":0,"verifiedAt":"2026-11-26T00:00:00.000Z","curated":true,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:42.912Z","updatedAt":"2026-11-26T16:00:42.912Z"},{"id":"6b0857be3c96f2d34d0b4208","type":"article","provider":"web","url":"https://refactoring.guru/design-patterns/decorator","embedUrl":null,"title":"Decorator","description":"Decorator is a structural design pattern that lets you attach new behaviors to objects by placing these objects inside special wrapper objects that contain the behaviors.","author":"Refactoring.Guru","thumbnailUrl":"https://refactoring.guru/images/refactoring/social/facebook-share-preview.png?id=dbf9e98269595be86eb668f365be6868","durationSec":null,"lang":"en","topics":["decorator"],"techs":["general"],"tags":["design-patterns"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"manual","publishedAt":null,"popularity":75,"verifiedAt":"2026-11-26T11:26:02.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:59.965Z","updatedAt":"2026-11-26T16:00:59.965Z"},{"id":"6b0857c33c96f2d34d0b4666","type":"book","provider":"openlibrary","url":"https://openlibrary.org/works/OL16942701W","embedUrl":null,"title":"Head First design patterns","description":"","author":"Eric Freeman, Elisabeth Freeman, Kathy Sierra, Bert Bates","thumbnailUrl":"https://covers.openlibrary.org/b/id/388950-L.jpg","durationSec":null,"lang":"en","topics":["factory-method","abstract-factory","builder","prototype","singleton","adapter","bridge","composite","decorator","facade","flyweight","proxy","chain-of-responsibility","command","iterator","mediator","memento","observer","state","strategy","template-method","visitor"],"techs":["java"],"tags":["book","design-patterns"],"price":"paid","featured":false,"featuredOrder":0,"packageName":null,"source":"openlibrary","publishedAt":"2004-01-01T00:00:00.000Z","popularity":62,"verifiedAt":"2026-11-26T11:00:08.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:04.995Z","updatedAt":"2026-11-26T16:01:04.995Z"}],"challenges":[{"id":"6b0857af5a2625e44ecaad13","slug":"design-patterns-basics-quiz","title":"Design patterns – basics","summary":"Six questions about classic GoF patterns: groups, intent and differences.","servedLang":"en","availableLangs":["pl","en"],"kind":"quiz","category":null,"status":"published","difficulty":"easy","topics":["builder","adapter","strategy","decorator","composite","facade","observer"],"techs":["general"],"tags":["quiz","gof","basics"],"languages":[],"questionCount":6,"xp":10,"stats":{"attempts":1,"solves":1,"solutions":0,"comments":0},"solveRate":100,"publishedAt":"2026-11-26T16:00:47.960Z"},{"id":"6b093ddebd4755deb67ee080","slug":"lru-cache","title":"LRU cache","summary":"A fixed-capacity cache that evicts the least recently used entry when full. get and put in O(1) – a map plus a doubly linked list.","servedLang":"en","availableLangs":["pl","en"],"kind":"code","category":"algorithms","status":"published","difficulty":"medium","topics":["proxy"],"techs":["typescript","javascript","python","dotnet","java","go"],"tags":["design","hash-map","linked-list","caching","data-structures"],"languages":["typescript","javascript","python","csharp","java","go"],"questionCount":null,"xp":20,"stats":{"attempts":0,"solves":0,"solutions":0,"comments":0},"solveRate":null,"publishedAt":"2026-11-27T08:22:54.691Z"},{"id":"6b093ddebd4755deb67ee06e","slug":"flatten-object","title":"Flatten a nested object","summary":"Turn a nested JSON object into a flat path → value map (e.g. for a CSV export or a config diff). Recursion or an explicit stack, leaves and empty containers.","servedLang":"en","availableLangs":["pl","en"],"kind":"code","category":"algorithms","status":"published","difficulty":"easy","topics":["composite"],"techs":["typescript","javascript","python"],"tags":["recursion","objects","dfs","javascript"],"languages":["typescript","javascript","python"],"questionCount":null,"xp":10,"stats":{"attempts":0,"solves":0,"solutions":0,"comments":0},"solveRate":null,"publishedAt":"2026-11-27T08:22:54.109Z"},{"id":"6b093dddbd4755deb67ee061","slug":"debounce-throttle","title":"Debounce and throttle","summary":"Two classic frontend higher-order functions – debounce (call after silence) and throttle (at most once per period) – with cancel, flush, preserved this and injected timers.","servedLang":"en","availableLangs":["pl","en"],"kind":"code","category":"algorithms","status":"published","difficulty":"medium","topics":["decorator"],"techs":["typescript","javascript"],"tags":["javascript","closures","timers","event-loop","higher-order-functions"],"languages":["typescript","javascript"],"questionCount":null,"xp":20,"stats":{"attempts":0,"solves":0,"solutions":0,"comments":0},"solveRate":null,"publishedAt":"2026-11-27T08:22:53.681Z"},{"id":"6b093dc291bd8fbaf2a0c8e0","slug":"rate-caching-proxy","title":"Exchange-rate caching proxy","summary":"Two proxies in front of a slow bank API – a caching one with an entry lifetime and a lazy one that connects only on first use. They share one interface, so they compose.","servedLang":"en","availableLangs":["pl","en"],"kind":"code","category":"pattern","status":"published","difficulty":"medium","topics":["proxy"],"techs":["typescript","javascript","python","dotnet","java","go"],"tags":["proxy","caching","lazy-loading","ttl","structural"],"languages":["typescript","javascript","python","csharp","java","go"],"questionCount":null,"xp":20,"stats":{"attempts":0,"solves":0,"solutions":0,"comments":0},"solveRate":null,"publishedAt":"2026-11-27T08:22:26.583Z"},{"id":"6b093dc191bd8fbaf2a0c8c4","slug":"expense-approval-chain","title":"Expense approval chain","summary":"An expense travels through links – receipt check, team lead, manager, director – until someone approves or rejects it. Chain of Responsibility with pluggable links.","servedLang":"en","availableLangs":["pl","en"],"kind":"code","category":"pattern","status":"published","difficulty":"easy","topics":["chain-of-responsibility"],"techs":["typescript","javascript","python","dotnet","java","go"],"tags":["chain-of-responsibility","approval-workflow","behavioral","middleware"],"languages":["typescript","javascript","python","csharp","java","go"],"questionCount":null,"xp":10,"stats":{"attempts":0,"solves":0,"solutions":0,"comments":0},"solveRate":null,"publishedAt":"2026-11-27T08:22:25.083Z"}],"attachments":[],"hasCode":true,"repoUrl":null,"series":[{"slug":"gof-structural","title":"GoF structural patterns","items":[{"slug":"adapter","title":"Adapter – how to get along with code that speaks another language","current":false},{"slug":"bridge","title":"Bridge – two axes of change without a class explosion","current":false},{"slug":"composite","title":"Composite – trees in which a leaf and a branch look the same","current":false},{"slug":"decorator","title":"Decorator – adding behaviour layer by layer","current":true},{"slug":"facade","title":"Facade – one simple entry point to a complex subsystem","current":false},{"slug":"flyweight","title":"Flyweight – how to fit 60,000 stadium seats in memory","current":false},{"slug":"proxy","title":"Proxy – a stand-in that controls access to the real object","current":false}]}],"prev":{"slug":"composite","title":"Composite – trees in which a leaf and a branch look the same"},"next":{"slug":"facade","title":"Facade – one simple entry point to a complex subsystem"},"featured":false,"authorCard":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","headline":"Wzorce projektowe · Architektura · AI i LLM","community":false,"reputation":{"points":3900,"level":{"key":"mentor","label":"Mentor"}},"articles":68,"skills":[{"key":"typescript","title":"TypeScript","level":5,"levelLabel":"Authority","articles":63},{"key":"dotnet","title":".NET","level":5,"levelLabel":"Authority","articles":53},{"key":"python","title":"Python","level":5,"levelLabel":"Authority","articles":52},{"key":"java","title":"Java","level":5,"levelLabel":"Authority","articles":38}]}}