Repaso
EspaƱol
Design & PracticesIntermediateDP-10

Which pattern is this?

class Checkout:
    def __init__(self, shipping_calc):
        self.shipping_calc = shipping_calc

    def total(self, cart):
        return cart.subtotal + self.shipping_calc(cart)

Checkout(express_shipping).total(cart)
Checkout(free_shipping).total(cart)

Options

  1. Strategy (Correct option)
  2. Observer
  3. Adapter
  4. Template Method

Answer

Strategy

Why

Strategy puts interchangeable algorithms (here: ways to calculate shipping) behind the same interface, and lets you choose one at runtime.

Checkout does not know or care which shipping rule it got; it just calls it. Adding a new rule needs no change in Checkout.

In Python a strategy can simply be a function.

Remember

Strategy = swap the algorithm without changing the code that uses it.

Key terms

Practice this question in Repaso