AlgoViz

Strategy pattern

medium 55 min

Define a family of interchangeable algorithms behind one interface.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:30

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

strategypageCheckoutPagecartShoppingCarttotal15000receiptnonecardCardPaymentlast four4444paypalPayPalPaymentfee3 percentcryptoCryptoPaymentminimum1000

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

samCommuternavNavigatormiles5minutes100walkingWalkingdrivingDrivingtransitTransitbuild_route100 min

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

    critical

    The cart still knows every class, so nothing was gained.

    Wrong
    def checkout(self, kind):    if kind == "card":        self._payment = CardPayment()
    Right
    def __init__(self, payment):    self._payment = payment
  • No strategy at all

    major

    The first checkout fails with a message about None.

    Wrong
    def __init__(self):    self._payment = None
    Right
    def __init__(self, payment):    self._payment = payment
  • Parameters that most ignore

    major

    Each new way changes the signature of all ways.

    Wrong
    def pay(self, amount, card, email, wallet): ...
    Right
    CardPayment(token).pay(amount)
  • A shared strategy with customer data

    critical

    Two requests overwrite each other's card.

    Wrong
    CARD = CardPayment()CARD.token = request.token
    Right
    payment = CardPayment(request.token)
  • Fallback after a timeout

    critical

    The first provider may have charged already.

    Wrong
    except Timeout:    return backup.pay(amount)
    Right
    except Timeout:    return resolve(provider, key)
  • Asking for the type

    major

    The context depends on a concrete class again.

    Wrong
    if isinstance(self._payment, PayPal):    total += 600
    Right
    receipt.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.