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