Design a parking lot
medium 90 minModel a car park with several levels as classes: vehicles, spaces of different sizes, tickets and a replaceable price rule.
Watch lesson4:48
Display board
Observer, order, and slow listeners
The point: when several things must react to one change and the list will grow, let them subscribe. Then take care of order, slowness and failure, which the textbook picture leaves out.
Observer
Who wants to know
Signs listen. The lot does not know them.
1/2One small interface
The lot says: something changed, this is message number 41, these are the free counts. It knows nothing about lamps or phones.
usesimplements
| Listener | Uses | Reacts |
|---|---|---|
| Sign at the entrance | All sizes | FULL when nothing is left |
| Sign on each level | Its own level | A number and an arrow |
| Phone app | The total | A message when 10 or fewer are left, once, not at 9 and 8 again |
| Light over a space | One space | Green or red |
| Statistics | Every change | Writes to a queue |
Bugs
The textbook version has five
| Textbook | What goes wrong | Repair |
|---|---|---|
ArrayList of observers | Subscribe during a notification: an exception, or a lost observer | An immutable list that is replaced, or CopyOnWriteArrayList |
total += delta without a lock | Two gates, one update lost: 3 minus 1 minus 1 is 2 instead of 1 | Change counts under the lock |
| Notify inside the lock | A slow sign stops all gates. A listener that calls back may never return | Copy under the lock, call after it |
| Notify outside the lock | Two messages may arrive in the wrong order: FULL, then 1 | A version number; older messages are dropped |
| One exception ends the loop | A broken sign silences the others | Catch for each listener and log |
Python
from threading import Lockfrom typing import CallableListener = Callable[[int, dict[str, int]], None] # version, free countsclass Counter: def __init__(self, counts: dict[str, int]) -> None: self._lock = Lock() self._counts = counts self._version = 0 self._listeners: tuple[Listener, ...] = () # replaced, never edited def subscribe(self, listener: Listener) -> None: with self._lock: self._listeners += (listener,) def change(self, size: str, by: int) -> None: with self._lock: self._counts[size] += by self._version += 1 version, snapshot, listeners = self._version, dict(self._counts), self._listeners for listener in listeners: # outside the lock try: listener(version, snapshot) except Exception as problem: # one broken sign must not stop the gate print("sign failed:", problem)class Board: def __init__(self, name: str) -> None: self.name, self.shows, self._seen = name, "", 0 def __call__(self, version: int, free: dict[str, int]) -> None: if version <= self._seen: return # an older message that came late self._seen = version self.shows = "FULL" if not any(free.values()) else " ".join(f"{k} {v}" for k, v in free.items())counter, entrance = Counter({"M": 1}), Board("entrance")counter.subscribe(entrance)counter.subscribe(lambda version, free: 1 / 0)counter.change("M", -1)print(entrance.shows)entrance(0, {"M": 9})print(entrance.shows)Why the version is needed
How do signs learn about changes?
BreaksThe lot calls each sign
- How
entranceBoard.update(); app.push();insideenter.- Limit
- A new sign is a change in the lot, and a slow one stops the gate.
- Choose when
- Never with more than one.
WorksSigns ask every second
- How
free()on a timer.- Limit
- Up to a second old, and useless questions at night.
- Choose when
- A handful of signs. It is simple, it cannot lose a message, and it recovers by itself.
StrongSubscribe, with versions and a queue
- How
- The lot puts (version, counts) in a queue for each listener, size one, newest wins. A thread for each listener sends.
- Limit
- More parts. And still a full refresh now and then, in case a message is lost.
- Choose when
- Many listeners, or changes must show at once.