Home [Fluent Python] Ch10. Refactoring Strategy Pattern with First-Class Functions
Post
Cancel

[Fluent Python] Ch10. Refactoring Strategy Pattern with First-Class Functions

Classic Strategy

Strategy Pattern is a good example that can be simplified using Python first-class functions.

Strategy Pattern

The Strategy pattern defines a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it

One good example of Strategy applied in the e-commerce domain is “computing discounts to orders according to the customer’s attributes or the property of orders”. For example,

  • Customers with more than 1000 fidelity score gets a global 5% discount
  • A 10% discount is applied to each line item with 20 or more units in the same order
  • Orders with at least 10 distinct items get a 7% global discount.

  • Context
    • Provides a service by delegating some computation to interchangeable components that implement alternative algorithms.
    • In ecommerce example, the context is an Order.
  • Strategy
    • The interface common to the components that implement different algorithms.
    • In ecomomerce example, the role strategy is played by ABC Promotion
  • Concrete Strategy
    • Concrete subclass of Strategy
      • FidelityPromo, BulkPromo, and LargeOrderPromo

Strategy Pattern Implementation with Classes

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
from abc import ABC, abstractmethod
from collections.abc import Sequence
from decimal import Decimal
from typing import NamedTuple, Optional

class Customer(NamedTuple):
  name: str
  fidelity: int

class LineItem(NamedTuple):
  product: str
  quantity: int
  price: Decimal

  def total(self) -> Decimal:
    return self.price * self.quantity


class Order(NamedTuple): # Context
  customer: Customer
  cart: Sequence[LineItem]
  promotion: Optional[Promotion] = None

  def total(self) -> Decimal:
    totals = (item.total() for item in self.cart)
    return sum(totals, start=Decimal(0))

  def due(self) -> Decimal:
    if self.promotion is None:
      discount = Decimal(0)
    else:
      discount = self.promotion.discount(self)
    return self.total() - discount


class Promotion(ABC): # Strategy: an ABC
  @abstractmethod
  def discount(self, order: Order) -> Decimal:
    """Return discount as a positive dollar amount"""


class FidelityPromo(Promotion): # Concrete Strategy
  def discount(self, order: Order) -> Decimal:
    if order.customer.fidelity >= 1000:
      return order.total() * 0.05
    return Decimal(0)


class BulkItemPromo(Promotion): # Concrete Strategy
  """10% discount for each item with 20 or more units"""

  def discount(self, order: Order) -> Decimal:
    # Some logics here...
    pass


class LargeOrderPromo(Promotion):
  """7% discount for orders with 10 or more distinct items"""
  
  def discount(self, order: Order) -> Decimal:
    # Some logics here...
    pass
  • An Order is a context which delegates promotion discount computation to specific Strategy (FidelityPromo, etc).
  • Promotion is the strategy implemented with ABC.
  • FidelityPromo, BulkItemPromo, LargeOrderPromo are concrete strategies.

Below is a sample usage of Order class with different promotions

1
2
3
4
5
6
7
8
9
10
11
jason = Customer("Jason Lee", 0)
andy = Customer("Andy Mac", 1100)

cart = (
  LineItem('banana', 4, Decimal('.5')),
  LineItem('apple', 10, Decimal('1.5')),
  LineItem('watermelon', 5, Decimal(5))
)

Order(jason, cart, FidelityPromo()) # total: 42.00, due: 42.00
Order(andy, cart, FidelityPromo()) # total: 42.00, due: 39.90
This post is licensed under CC BY 4.0 by the author.
Trending Tags