Proxy pattern
medium 50 minA 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
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
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
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
criticalThe layout asks every photo for its size.
Wrongdef size(self): return self._real_image().size()Rightdef size(self): return self._size # from the indexGiving out the real object
criticalThe check is one attribute away from being skipped.
Wrongclass AccountProxy: def unwrap(self): return self._realRightdef account_for(user): return AccountProxy(_real, user, policy, audit)Check without lock
majorTwo threads create two.
Wrongif self._real is None: self._real = load()Rightwith self._lock: if self._real is None: self._real = load()A new id for every attempt
criticalThe server can not know that it is a repeat.
Wrongfor _ in range(3): send(new_id(), cents)Rightrequest_id = new_id()for _ in range(3): send(request_id, cents)Storing a failure
majorOne hiccup answers for a whole minute.
Wrongexcept OSError: value = Noneself._memo[sku] = valueRightvalue = 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.