AlgoViz

Proxy pattern

medium 50 min

A proxy stands in for another object, with the same interface, and controls access to it: it creates it late, checks the caller, remembers results, or reaches it over a network.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:53

See it run

Objects at run time: which calls reach the real object, and which do not.

Operations

Lazy image

An album of proxies. One picture is opened twice.

Step 1 of 7

Three proxies

galleryGallerymemory MB0vacationImageProxyrealnoneweddingImageProxyrealnonegraduationImageProxyrealnone

Each knows a name and a size. No pixels.

Step 1: Three proxies

class ImageProxy(Image):    def size(self):        return self._size    def display(self):        if self._real is None:            self._real = self._load(self._filename)        return self._real.display()
Watch
Memory
Result
50 MB, not 150

The arrow from the gallery never changes.

In the real world

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

Two threads meet an empty proxy.

Step 1 of 3

Both look

viewerThread 1printerThread 2imageImageProxyrealnoneloads0display()

Thread 1 sees none. Thread 2 sees none.

Step 1: Both look

Common mistakes

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

  • Loading in a cheap method

    critical

    The layout asks every photo for its size.

    Wrong
    def size(self):    return self._real_image().size()
    Right
    def size(self):    return self._size        # from the index
  • Giving out the real object

    critical

    The check is one attribute away from being skipped.

    Wrong
    class AccountProxy:    def unwrap(self): return self._real
    Right
    def account_for(user):    return AccountProxy(_real, user, policy, audit)
  • Check without lock

    major

    Two threads create two.

    Wrong
    if self._real is None:    self._real = load()
    Right
    with self._lock:    if self._real is None:        self._real = load()
  • A new id for every attempt

    critical

    The server can not know that it is a repeat.

    Wrong
    for _ in range(3):    send(new_id(), cents)
    Right
    request_id = new_id()for _ in range(3):    send(request_id, cents)
  • Storing a failure

    major

    One hiccup answers for a whole minute.

    Wrong
    except OSError: value = Noneself._memo[sku] = value
    Right
    value = self._real.price(sku)   # may raiseself._memo[sku] = value

Interview tips

  • One job

    • Whether, when, where, who.
    • Real class stays clean.
    • Bind it in a factory.
  • Guard

    • Deny by default.
    • Every method.
    • Wrap results.
  • Remember

    • Key, age, bound.
    • Who invalidates?
    • No errors.
  • Be honest

    • Show distance.
    • Type the failure.
    • Batch, do not loop.