pricing_strategy_normal_discount_shopping_cart.py
· 1.2 KiB · Python
Raw
from abc import ABC, abstractmethod
# 策略介面
class PricingStrategy(ABC):
@abstractmethod
def calculate_price(self, price):
pass
# 具體策略類
class NormalStrategy(PricingStrategy):
def calculate_price(self, price):
return price
class DiscountStrategy(PricingStrategy):
def __init__(self, discount_rate):
self.discount_rate = discount_rate
def calculate_price(self, price):
return price * (1 - self.discount_rate)
# 上下文類
class ShoppingCart:
def __init__(self, pricing_strategy):
self.pricing_strategy = pricing_strategy
def set_pricing_strategy(self, pricing_strategy):
self.pricing_strategy = pricing_strategy
def checkout(self, items):
total_price = sum(items)
return self.pricing_strategy.calculate_price(total_price)
# 使用範例
cart = ShoppingCart(NormalStrategy())
items = [100, 200, 300]
print("Total price with normal strategy:", cart.checkout(items)) # Output: Total price with normal strategy: 600
cart.set_pricing_strategy(DiscountStrategy(0.2))
print("Total price with discount strategy:", cart.checkout(items)) # Output: Total price with discount strategy: 480
| 1 | from abc import ABC, abstractmethod |
| 2 | |
| 3 | # 策略介面 |
| 4 | class PricingStrategy(ABC): |
| 5 | @abstractmethod |
| 6 | def calculate_price(self, price): |
| 7 | pass |
| 8 | |
| 9 | # 具體策略類 |
| 10 | class NormalStrategy(PricingStrategy): |
| 11 | def calculate_price(self, price): |
| 12 | return price |
| 13 | |
| 14 | class DiscountStrategy(PricingStrategy): |
| 15 | def __init__(self, discount_rate): |
| 16 | self.discount_rate = discount_rate |
| 17 | |
| 18 | def calculate_price(self, price): |
| 19 | return price * (1 - self.discount_rate) |
| 20 | |
| 21 | # 上下文類 |
| 22 | class ShoppingCart: |
| 23 | def __init__(self, pricing_strategy): |
| 24 | self.pricing_strategy = pricing_strategy |
| 25 | |
| 26 | def set_pricing_strategy(self, pricing_strategy): |
| 27 | self.pricing_strategy = pricing_strategy |
| 28 | |
| 29 | def checkout(self, items): |
| 30 | total_price = sum(items) |
| 31 | return self.pricing_strategy.calculate_price(total_price) |
| 32 | |
| 33 | # 使用範例 |
| 34 | cart = ShoppingCart(NormalStrategy()) |
| 35 | items = [100, 200, 300] |
| 36 | print("Total price with normal strategy:", cart.checkout(items)) # Output: Total price with normal strategy: 600 |
| 37 | |
| 38 | cart.set_pricing_strategy(DiscountStrategy(0.2)) |
| 39 | print("Total price with discount strategy:", cart.checkout(items)) # Output: Total price with discount strategy: 480 |
| 40 |