Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 57 ยท Structural Patterns

Decorator

Learn the Decorator design pattern: wrap an object to add behavior at run time, stack decorators, and compare the pattern with Python and JavaScript decorators.

The Decorator pattern adds behavior to an object by wrapping it in another object that has the same interface. The wrapper forwards each call to the thing inside, and does something extra before or after. Because a decorator looks exactly like what it wraps, you can wrap a decorator in another decorator, and stack as many as you need.

It is the alternative to subclassing for optional extras. Imagine a coffee shop where every drink can get milk, sugar, whipped cream or an extra shot. With inheritance you would need CoffeeWithMilk, CoffeeWithMilkAndSugar, CoffeeWithSugarAndWhip and so on, one class per combination. With decorators you write Milk, Sugar and Whip once and combine them when you build the order.

Wrap, don't subclass

Same interface A wrapper looks exactly like the thing it wraps.
Layers Wrappers can wrap wrappers, in any order.
Run time You choose the extras while the program runs.

Combinations come from composition, not from new subclasses.

1 / 2

The structure

A decorator implements the same component interface as the object it wraps and keeps a reference to it. The wrapped object may be a plain concrete component or another decorator.

classDiagram
    class Beverage {
        <<interface>>
        +cost()
        +describe()
    }
    class Espresso
    class AddOn {
        <<abstract>>
        -inner
    }
    class Milk
    class Sugar
    Beverage <|.. Espresso
    Beverage <|.. AddOn
    AddOn <|-- Milk
    AddOn <|-- Sugar
    AddOn o--> Beverage : wraps

An add-on is itself a beverage and holds a beverage, so add-ons can be stacked without limit.

A coffee order

Each decorator calls the wrapped drink for its own cost and description, then adds its part. The order is built from the inside out.

JS Stacking add-ons on a drink

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The last order wraps the espresso in sugar and then in two extra shots. The same DoubleShot class is used twice, which a class-per-combination design could not do without yet another class.

Order matters sometimes

Decorators that only add are commutative, but decorators that transform a result are not. A "10 percent discount" and a "plus $1 service fee" give different totals depending on which wraps which. When order matters, document it, or build the stack in a function so callers cannot get it wrong.

JS Decorators that transform data

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In the first stack the text enters brackets, which passes it inward to exclaim, then upper, then trim. The innermost layer returns first, and exclaim appends its ! before brackets wraps the result, giving [HELLO WORLD!]. In the second stack exclaim sits outside brackets, so the ! lands after the closing bracket: [HELLO WORLD]!. Same decorators, different order, different output.

Decorators in Python and JavaScript

Python's @decorator syntax and the proposal for JavaScript decorators on classes are language features that look a lot like this pattern, and they are closely related, but they are not the same thing:

  • The pattern is object-oriented: a wrapper object implements the same interface as another object and you compose them at run time.
  • A Python function decorator is a function that takes a function and returns a wrapped function. It is the Decorator idea applied to callables, evaluated once when the function is defined.

The Python example below does both. It writes the pattern with classes, then shows the same idea with @ on functions. Notice that functools.wraps copies the original function's name and docstring onto the wrapper, so tools that inspect the function still see the right information.

Python The pattern and Python's @ syntax

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

@counted on top of @shout means greet = counted(shout(greet)): decorators apply from the bottom up, exactly like wrapping the innermost object first.

When to use it, and when not to

Use Decorator when:

  • you want to add responsibilities to individual objects at run time, not to a whole class;
  • extension by subclassing would produce an explosion of classes, or the class is final or otherwise closed;
  • the extras are independent and should be combinable.

Real examples are Java's I/O streams (new BufferedReader(new InputStreamReader(...)) stacks buffering on top of decoding), middleware that wraps a request handler, and logging, caching or retry wrappers around a service client.

Be careful about these costs:

  • Many small objects. A heavily decorated object is a chain of wrappers that can be hard to debug, because the stack trace passes through each layer.
  • Identity. A decorated object is not the same object as the original, so == or instanceof checks against the concrete class can fail.
  • Interface growth. If the component interface is large, every decorator must forward every method, which is tedious. Keep the interface small.
  • Order sensitivity. As shown above, wrapping order can change behavior.

It is also easy to confuse with its relatives. Proxy wraps an object too, but controls access to it and normally manages the wrapped object's lifecycle itself. Adapter changes the interface; a decorator keeps it. Composite holds many children; a decorator wraps exactly one. Strategy changes the guts of an object, while a decorator changes its skin.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What must a decorator have in common with the object it wraps?

    A decorator implements the component interface, which is why clients cannot tell a decorated object from a plain one and why decorators can be stacked.
  2. 2. A shop offers 5 drinks and 4 optional extras that can be combined in any way, including repeats. Which approach avoids creating a class for every combination?

    With decorators you write one class per extra and combine them at run time, so classes grow by addition rather than by multiplication.
  3. 3. In Python, what does @counted above @shout on a function mean?

    Decorators apply from the bottom up, so the function is wrapped by shout first and the result is then wrapped by counted.
  4. 4. How is Decorator different from Proxy, given that both wrap an object?

    Both wrap, but intent differs. A decorator enriches the object with new responsibilities; a proxy stands in for it to control creation, access, caching or logging.
  5. 5. Why use functools.wraps inside a Python decorator?

    Without it, introspection sees the wrapper's name and docs instead of the original function's, which confuses debuggers and documentation tools.

Summary

  • A decorator wraps an object that has the same interface and adds behavior before or after delegating.
  • Decorators can be stacked; the stacking order can change results when they transform data.
  • It replaces a class-per-combination subclass explosion with composition chosen at run time.
  • Python's @ and function wrappers in JavaScript apply the same idea to functions, evaluated when the function is defined.
  • Costs are many small objects, harder debugging, and changed object identity.
  • Decorator keeps the interface; Adapter changes it; Proxy controls access; Composite holds many children.

Next lesson: Facade.