Strategy pattern
medium 55 minDefine a family of interchangeable algorithms behind one interface.
Video lesson · Chapter 1 of 6
Make a prediction
See it run
Objects at run time: who holds which way, and who chose it.
Operations
Checkout
Three purchases, three ways, one cart. The arrow from the cart is its current strategy.
Step 1 of 9
A cart with a card
The cart was created with a card. It holds 150 dollars, as 15000 cents.
Step 1: A cart with a card
class ShoppingCart: def set_payment(self, payment): self._payment = payment def checkout(self): total = sum(self._prices) if not self._payment.can_pay(total): raise PaymentRefused receipt = self._payment.pay(total) self._prices.clear() return receipt- Watch
- The strategy arrow
- Result
- Same call, other receipt
Follow the arrow, not the buttons.
In the real world
The same strategy pattern doing real jobs. Pick one and step through it.
Five miles, three ways to travel.
Step 1 of 3
For exercise
Walking: pavements, parks and safe crossings, about 100 minutes.
Step 1: For exercise
Common mistakes
The bugs interviewers watch for, with the fix beside each.
The branch stays in the context
criticalThe cart still knows every class, so nothing was gained.
Wrongdef checkout(self, kind): if kind == "card": self._payment = CardPayment()Rightdef __init__(self, payment): self._payment = paymentNo strategy at all
majorThe first checkout fails with a message about None.
Wrongdef __init__(self): self._payment = NoneRightdef __init__(self, payment): self._payment = paymentParameters that most ignore
majorEach new way changes the signature of all ways.
Wrongdef pay(self, amount, card, email, wallet): ...RightCardPayment(token).pay(amount)A shared strategy with customer data
criticalTwo requests overwrite each other's card.
WrongCARD = CardPayment()CARD.token = request.tokenRightpayment = CardPayment(request.token)Fallback after a timeout
criticalThe first provider may have charged already.
Wrongexcept Timeout: return backup.pay(amount)Rightexcept Timeout: return resolve(provider, key)Asking for the type
majorThe context depends on a concrete class again.
Wrongif isinstance(self._payment, PayPal): total += 600Rightreceipt.fee # the strategy says so
Interview tips
Prove the family
- One verb.
- Same input.
- Same kind of answer.
Place things well
- Differences: constructor.
- Shared: method.
- Choice: one place.
Keep it small
- A value: parameter.
- One method: function.
- More: class.
In production
- One read per call.
- Unknown is not no.
- Log the name.