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

See it run

Objects at run time: who wraps whom, and what each layer adds.

Operations

Coffee, layer by layer

Wrap an espresso three times, then ask for the price.

Step 1 of 9

Espresso

clientClientespressoEspressoadds200

The concrete component. It costs 200.

Step 1: Espresso

coffee = Espresso()coffee = Milk(coffee)coffee = Sugar(coffee)coffee = WhippedCream(coffee)coffee.cost()class Milk(CoffeeDecorator):    def cost(self):        return super().cost() + 50
Watch
The client's arrow
Result
340 cents

The client always holds the outermost layer.

In the real world

The same decorator pattern doing real jobs. Pick one and step through it.

A cache decorator that loads each key once.

Step 1 of 3

Asha asks first

ashaThread 1samThread 2cachedCachedtealoadingpricesSlowPricescalls1price(tea)

The key is unknown. A promise is stored, and Asha's thread loads.

Step 1: Asha asks first

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Forgetting the assignment

    major

    The wrapper is created and thrown away.

    Wrong
    Milk(coffee)coffee.cost()        # 200
    Right
    coffee = Milk(coffee)coffee.cost()        # 250
  • Repeating the inner value

    major

    Right for espresso, wrong for anything else.

    Wrong
    class Milk(CoffeeDecorator):    def cost(self): return 250
    Right
    class Milk(CoffeeDecorator):    def cost(self): return super().cost() + 50
  • Cache around the check

    critical

    A hit gives one user another user's data.

    Wrong
    Cache(Authorize(service))
    Right
    Authorize(Cache(service))
  • One try around everything

    critical

    A failing log repeats or hides the payment.

    Wrong
    try:    r = inner.pay(x); log(r)except Exception: return None
    Right
    r = inner.pay(x)try: log(r)except Exception: errors.add(1)return r
  • Closing the inside

    major

    The buffer's last bytes go nowhere.

    Wrong
    out = Buffered(file)file.close()
    Right
    out = Buffered(file)out.close()          # flushes, then closes file

Interview tips

  • Base first

    • Forward everything once.
    • Refuse a missing inside.
    • Keep the interface small.
  • Order

    • Outside sees first.
    • Authorize outside cache.
    • Buffer next to the disk.
  • State

    • Share on purpose.
    • Never lock a slow call.
    • Bound every cache.
  • Know the leaks

    • Identity.
    • Self calls.
    • Extra methods.