Skip to content

Design Patterns

Decorator

Each layer adds O(1) extra work (a constant amount). So n layers cost O(n) total — the total time grows along with the number of layers.

The idea, in plain English

A decorator works like wrapping a gift. You start with a plain box, then add wrapping paper, then a bow. Each layer adds something extra without changing what's inside. In code, a decorator wraps a simple object and adds extra behavior, one layer at a time.

How it works

  1. 1Start with a simple base thing that does the core job.
  2. 2Wrap it in a decorator that calls the base and adds a bit extra.
  3. 3Wrap that result in another decorator, and so on. Each layer adds one more thing.

When you'd use it

Use this when you want to add features — like logging, milk in a coffee, or extra formatting — without changing the original code. You can then mix and match those extras freely.

Common beginner mistakes

  • Don't stack so many decorators that no one can tell what the final behavior actually is.
  • Always call the wrapped thing inside your decorator, or the original behavior gets lost.

Try it — edit and run

Click the code to edit · press ⌘/Ctrl+↵ to run

Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.

Expected output — hit Run to try it
Coffee + Milk + Sugar

Not sure this is the right topic? See the learning paths → or where this leads →