Facade pattern
easy 50 minThe Facade pattern gives a group of classes one simple front.
Video lesson · Chapter 1 of 6
Make a prediction
See it run
Who calls whom, in which order, and what is left behind when a step fails.
Operations
By hand
A client starts five devices without a facade.
Step 1 of 7
Five devices
All off, the lights are bright. The client has to know each class.
Step 1: Five devices
def movie_night(tv, speakers, dvd, lights, projector): tv.turn_on() tv.set_channel(3) speakers.turn_on() speakers.set_volume(50) lights.dim(10) dvd.turn_on() dvd.play("Inception") # and the projector?- Watch
- The order of calls
- Result
- Easy to get wrong
The client needs a manual for every device.
In the real world
The same facade pattern doing real jobs. Pick one and step through it.
A facade with too many methods. Which belong together?
Step 1 of 4
Fill in
| stock | payment | shipping | ledger | accounts | |
|---|---|---|---|---|---|
| place_order | uses | uses | uses | ||
| cancel_order | uses | uses | uses | ||
| print_label | uses | ||||
| tax_export | uses | ||||
| report | uses | ||||
| new_password | uses |
Which part does each method touch? Helpers that all use, such as mail and log, are left out.
Step 1: Fill in
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Getters for the parts
majorClients depend on the parts again, with one more dot.
Wrongtheater.speakers().set_volume(65)Righttheater.watch_movie("Inception", Scene(volume=65))Rules in the front
majorThe next entrance will not have the rule.
Wrongdef watch_movie(self, movie, guest): if guest.age < movie.age: raise ...Rightpolicy.require_may_watch(guest, movie)theater.watch_movie(movie)No way back
criticalThe card is charged, the order does not exist.
Wrongself._payment.charge(key, cents)self._shipping.schedule(key, to)Rightself._payment.charge(key, cents)undo.append(refund)self._shipping.schedule(key, to)Stopping at the first error
criticalOne stuck device keeps the projector burning.
Wrongdef end_movie(self): self._dvd.turn_off() self._projector.off()Rightfor off in steps: try: off() except Exception as e: report(e)Mail inside the sequence
majorA sleeping mail server refunds a paid order.
Wrongself._mailer.send(mail) # inside the tryRightself._outbox.add(mail) # after it, with the orderOne facade for everybody
major45 methods, and each client needs three.
Wrongclass ShopFacade: ... # orders, tax, passwordsRightclass OrderFacade: ...class FinanceFacade: ...
Interview tips
Start outside
- Collect wishes.
- Use the client's words.
- Two to ten methods.
Keep arrows one way
- Client to front to parts.
- Parts come from outside.
- Own result types.
Plan the way back
- Undo after each effect.
- Reverse order.
- Stop everything you can.
Over a network
- One wish, one request.
- Required or optional.
- A budget of time.
Watch it grow
- Callers per method.
- Parts per method.
- Split by client.