AlgoViz

Decorator pattern

medium 45 min

Decorator adds behaviour to one object by wrapping it in another with the same interface.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:34

Decorator

1:04Reel

More reels

One idea each, a minute or less.

Play all in Bytesized Learning

Decorator vs proxy

0:32Reel

Theory

Read or listen first. About 1 min.

What it is

Decorator is a structural design pattern. An object is put inside another object that has the same interface, forwards calls to it, and adds something before, after or around them.

A decorator is a component and has a component. Because of the first it can be used anywhere the original could. Because of the second it can ask the original. Together they allow decorators around decorators.

The object inside is never changed. Each object can wear its own set of layers.

Why it exists

Subclasses fix a combination when you compile, and the number of combinations doubles with each optional extra.

With decorators each extra is one class, written once, and combinations are made at run time, for one object.

Extras such as logging, caching, retry, buffering and checking stay out of the class that does the real work. That class keeps one reason to change.

A short history

  1. 1994

    The book Design Patterns describes Decorator among its structural patterns, with scroll bars and borders around a text view as the example.

  2. 1996

    Java 1.0 ships stream classes that wrap streams: FilterInputStream and its subclasses are listed as since 1.0.

  3. 2003

    PEP 318 is created: the @ syntax for decorators of Python functions. It came with Python 2.4.

Words to know

Component
The interface shared by the object and its wrappers.
Concrete component
The object at the centre.
Base decorator
Holds a component and forwards everything.
Concrete decorator
Adds one responsibility.
Forwarding
Passing a call on to the object inside.
Layer, chain
One wrapper, and the whole line of them.
Transparent
Clients can not tell a wrapped object from a bare one by calling it.
Middleware
A decorator around a request handler.
Self call
An object calling its own method. It does not pass through the wrapper.

The solution, twice

Reach the regular design first. Then go where a FAANG interviewer digs.

How it works

Step through the idea, or press Play.

Step 1 of 3

Call arrives. At the outermost layer

Understand it

Start here

Dressed, but still the same snowman

You want to add something to one object: logging to this service, milk to this coffee, a buffer to this file. Not to all objects of the class, not for ever, and not by editing the class. The Decorator pattern puts the object into another one that looks the same from outside and adds its bit.

Sam dresses a snowman
100

However the snowman is dressed, Lee measures in the same way: once around the outside.

A wrapped birthday present is the same idea. A toy, a box around it, paper around the box, a ribbon around the paper. Each layer adds something, nobody changed the toy, and from outside it is still one present that you can hand over.

Four roles

  • Component

    The interface that the client uses: Coffee, InputStream, HttpClient.

  • Concrete component

    The object at the centre: Espresso, FileInputStream. It does the real work.

  • Decorator

    Is a component and has a component. Forwards everything. Usually abstract.

  • Concrete decorator

    Adds one thing before or after forwarding: Milk, BufferedInputStream.

Why

What goes wrong with subclasses

A coffee shop sells espresso. Then espresso with milk, then with sugar, then with both. With inheritance each combination is a class, and each combination is decided when you compile.

Python
class Espresso:    def cost(self): return 200class EspressoMilk(Espresso):    def cost(self): return 200 + 60          # new milk priceclass EspressoSugar(Espresso):    def cost(self): return 200 + 20class EspressoMilkSugar(Espresso):    def cost(self): return 200 + 60 + 20class EspressoMilkCream(Espresso):    def cost(self): return 200 + 50 + 70     # forgottenclass EspressoMilkSugarCream(Espresso):    def cost(self): return 200 + 60 + 20 + 70print("milk in the first:", EspressoMilk().cost() - Espresso().cost())print("milk in the fourth:", EspressoMilkCream().cost() - 200 - 70)print("double milk: no class for it")
Run it. The price of milk is in four classes. Somebody changed three of them.
Edit and run it in your browser

The explosion

subclasses=2ndecorators=n\text{subclasses} = 2^n \qquad \text{decorators} = n
4 optional toppings: 16 combinations against 4 decorators (plus one base class). Two kinds of coffee: 32 against the same 4. Double portions make the left side infinite.

The design that hurts

Espresso+ cost(): 200EspressoMilk+ cost(): 250EspressoSugar+ cost(): 220EspressoCream+ cost(): 270

1/3One coffee, three toppings

So far so good. Each subclass adds one topping.

extends (is a)

The smell: class names with And or With in them.

A wrapper per extra

  • n decorators and one base
  • Each rule in one place
  • Chosen at run time, per object
  • Any order, any number of times

A subclass per combination

  • 2 to the power of n classes
  • The same rule in many places
  • Fixed when you compile
  • No double portions

The idea

Is one, and has one

A decorator implements the interface, so it can stand wherever the original stood. It also holds an object of that interface, so it can ask for the original answer. These two facts together make nesting possible.

The Decorator pattern in general

Client+ holds a Component«interface»Component+ operation()

1/4The interface

The client knows Component and nothing else. It does not need to change when something is wrapped.

usesimplementshas (lives on)extends (is a)

The same drawing as Composite with one child instead of many.

What exists at run time

A line of four objects. The client holds the left end.

cost() goes in and comes out

200 + 50 + 20 + 70 = 340 cents, that is 3.40.

description() does the same with text

WhippedCream adds the last word. The order of wrapping is the order of reading.

Kinds

What a decorator may do around the call

PlaceExampleCode
Beforecheck the token, start a clockcheck(); return inner.get(x)
Afteradd a price, log the resultreturn inner.cost() + 50
Aroundmeasure, retry, transactiontry: ... finally: ...
Insteadanswer from a cacheif x in memo: return memo[x]
Change the argumentadd a header, encodeinner.send(encrypt(x))
Change the resultdecode, cut, sortreturn unzip(inner.read())
A decorator that usually answers instead is close to a Proxy.

Order

Which layer is outside?

With prices the order does not matter, because addition does not care. With almost everything else it does. Read a chain from the outside: the outer layer sees the request first and the answer last.

OutsideInsideMeaning
EncryptCompressCompress first, then encrypt: small and secret
CompressEncryptEncrypted data looks random and hardly gets smaller
RetryLogOne line per attempt
LogRetryOne line per request, attempts hidden
CacheAuthorizeA second user may get the first user's answer
AuthorizeCacheEveryone is checked, then the cache may answer
For writing: the outer layer handles the data first. For reading, bytes come from the inside, so the inner layer handles them first.

A service needs a cache and a permission check, both as decorators. Which goes outside?

BreaksCache outside, key is the id
How
Cache(Authorize(service)).
Limit
Asha's salary is cached. Sam asks for the same id and gets it without any check.
Choose when
Never.
WorksCache outside, key is user and id
How
The answer is stored per user.
Limit
Many more entries, and a permission that was taken away still answers until the entry ends.
Choose when
When the answer itself differs per user.
StrongAuthorize outside, cache inside
How
Authorize(Cache(service)). Every call is checked, the data is shared.
Limit
The check runs on every call, so it must be cheap.
Choose when
The default.

Choosing

When to use it and when not

Use it when

  • Extras are optional and combine freely
  • They differ per object, or change at run time
  • You can not or should not edit the class
  • The interface is small
  • Concerns such as logging, caching, retry surround the work

Leave it when

  • There is one fixed extra: put it in the class
  • The interface has thirty methods
  • Extras need the inside of the object
  • Callers compare identity or ask for the class
  • Milk is only a price: then a list of toppings is data

Decorator or something else?

Real cases

ComponentCentreDecorators
InputStreamfile, socket, memorybuffer, unzip, decipher, count
HTTP handleryour functionauth, logging, compression
HTTP clientsocket clientretry, timeout, cache, metrics
Widgettext areascroll bars, border, shadow
Collectionlistread only, synchronized, checked
Functionyour function@cache, @timer, @retry
RepositorySQLcache, audit, soft delete
Java
try (DataInputStream in = new DataInputStream(        new GZIPInputStream(            new BufferedInputStream(                new FileInputStream("data.gz"))))) {    int value = in.readInt();      // 4 bytes, unzipped, buffered, from disk}
Java I/O. Four layers: raw bytes, a buffer of 8192 bytes by default, unpacking, and typed reads. Closing the outer one closes all.

Summary

The whole topic in one minute.

Wrap the object in something that is one and has one. Forward everything, add one thing, leave the inside alone. n extras are n classes.

Read a chain from outside: the outer layer sees the request first. Authorize outside cache, buffer next to the slow thing, the layer with extra methods outermost.

In production: build the chain in one place, keep state per service or per request on purpose, close from outside in, and remember that identity, type checks and self calls see through the wrapper.

  • A decorator is a component and has a component.
  • It adds one thing, forwards the rest, and never changes the object inside.
  • n decorators replace 2 to the power of n subclasses.
  • The outer layer sees the request first. Order is a decision, not a detail.
  • Identity, wide interfaces and closing are the three places where wrappers leak.

Sources