다가 전략 객체에는 상태(객체 속성)가 없다. 구체적인 전략 객체가 일반 함수처럼 보인다면,
제대로 본 것이다. [예제
10
-
3
]은 [예제
10
-
1
]을 리팩터링한 코드로, 구체적인 전략을 간단히
함수로 변경하고
Promotion
추상 클래스를 제거했다.
3
예제
10-3
할인 전략을 함수로 구현한
Order
클래스
from collections.abc import Sequence
from dataclasses import dataclass
from decimal import Decimal
from typing import Optional, Callable, NamedTuple
class Customer(NamedTuple):
name: str
fidelity: int
class LineItem(NamedTuple):
product: str
quantity: int
price: Decimal
def total(self):
return self.price * self.quantity
@dataclass(frozen=True)
class Order: # 콘텍스트
customer: Customer
cart: Sequence[LineItem] ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month, and much more.