Skip to content
LLD Learn/Structural Patterns
Browsing as a guest. Sign in to save your progress and earn XP as you complete chapters.

Decorator

5 min read

You'll learn to

  • -Stack behavior onto an object at runtime without subclass explosion, using a coffee worked example
  • -Explain why Decorator beats inheritance when many combinations of features are possible
  • -Trace a stacked call, and explain why the order of decorators can matter
  • -Tell Decorator from the Python @decorator syntax, from Strategy and from subclassing

Decorator attaches additional responsibilities to an object dynamically, providing a flexible alternative to subclassing for extending behavior. It is the pattern that directly answers the composition-vs-inheritance chapter from earlier: whenever a feature set could combine in many ways, wrapping beats subclassing every combination.

An Analogy: Layers of Clothing

On a cold day you put on a shirt, then a sweater, then a coat. Each layer adds something (warmth, wind protection) and you are still the same person underneath. You can wear any combination, in the order you choose, and you did not need a separate kind of person for every outfit. Decorator works the same way: each wrapper adds a feature while the thing underneath keeps behaving as the same kind of thing.

  • -You, without any layers, are the base component (SimpleCoffee).
  • -Each layer is a decorator (MilkDecorator, ExtraShotDecorator): it adds one feature.
  • -Every layer is still something you can be asked about the same way, which is the shared interface (Coffee).

The Coffee Shop Example, Worked Through

A coffee ordering system needs to support any combination of milk, extra shots, and syrup on top of a base coffee, each adding its own cost. Modeling this with subclasses (CoffeeWithMilk, CoffeeWithMilkAndExtraShot, CoffeeWithMilkAndSyrupAndExtraShot...) requires one class per combination - it explodes combinatorially. Decorator instead wraps a Coffee in any number of decorators, each adding its own cost and description on top of whatever it wraps.

Stacking decorators instead of subclassing every combination
class Coffee(ABC):
    @abstractmethod
    def cost(self) -> float: ...
    @abstractmethod
    def description(self) -> str: ...

class SimpleCoffee(Coffee):
    def cost(self) -> float: return 2.00
    def description(self) -> str: return "Coffee"

class CoffeeDecorator(Coffee):           # base decorator - same interface as Coffee
    def __init__(self, coffee: Coffee):
        self._coffee = coffee

class MilkDecorator(CoffeeDecorator):
    def cost(self) -> float: return self._coffee.cost() + 0.50
    def description(self) -> str: return self._coffee.description() + " + Milk"

class ExtraShotDecorator(CoffeeDecorator):
    def cost(self) -> float: return self._coffee.cost() + 0.75
    def description(self) -> str: return self._coffee.description() + " + Extra Shot"

# Any combination, at runtime, with no new class needed per combination:
order = ExtraShotDecorator(MilkDecorator(SimpleCoffee()))
print(order.description(), order.cost())  # "Coffee + Milk + Extra Shot" 3.25

Tracing the Stack

  • -order.cost() is called on ExtraShotDecorator, the outermost layer.
  • -It calls cost() on what it wraps, MilkDecorator, which calls cost() on SimpleCoffee.
  • -SimpleCoffee answers 2.00. MilkDecorator adds 0.50 and returns 2.50. ExtraShotDecorator adds 0.75 and returns 3.25.

Each decorator knows only that it wraps a Coffee, so the chain can be any length. The same arithmetic shows why subclassing loses. With 3 add-ons there are 2 to the power 3, which is 8, possible combinations, so 8 subclasses; with 5 add-ons it is 32. Decorator needs exactly one class per add-on: 3 and 5.

Why This Beats Inheritance Here

The key structural fact: every decorator implements the exact same interface (Coffee) as the thing it wraps, and holds a reference to a Coffee - which could be a SimpleCoffee or another decorator. This is what makes stacking possible: MilkDecorator does not need to know whether it is wrapping a plain coffee or a coffee that already has three other decorators applied, because from its perspective, both are equally just "a Coffee." With N independent add-ons, subclassing needs up to 2^N classes; Decorator needs exactly N decorator classes, combined at runtime in any order.

Order Can Matter

For price add-ons the order does not change the total, but for behavior it often does. Suppose you wrap a data stream in a compression decorator and an encryption decorator. Compress first, then encrypt, and the data shrinks. Encrypt first, then compress, and almost nothing shrinks, because encrypted data looks random and random data does not compress. In a quick test, 12,000 bytes of repetitive text compressed to 61 bytes, while 12,000 random bytes stayed at about 12,011. When you design a decorator stack, think about what each layer sees.

Not to Be Confused With

  • -Python's @decorator syntax wraps a function to add behavior. It is a language feature that follows the same idea, but the pattern in this chapter wraps objects and is a design technique that exists in any language.
  • -Strategy swaps one algorithm for another, chosen from outside. Decorator adds to the behavior of the thing it wraps and can be stacked.
  • -Subclassing fixes the combination when you write the code. Decorators choose it at runtime.

A well-known real-world example of this exact pattern: Java and Python's I/O stream classes (BufferedReader wrapping a FileReader, GZIPInputStream wrapping a FileInputStream) are Decorators - each layer adds behavior while presenting the same stream interface.

Interview Signal is part of Pro

See a real weak answer next to a real strong one for this exact topic.

Quiz is part of Pro

Test what you just read with a short quiz, and bank the XP.

Discussion0

Join the Discussion

Sign in to leave comments, reply to others, or like insights.

Sign In to ScaleDojo

No comments yet. Be the first to start the thread!