Última actividad 10 months ago

這段程式碼實作「策略模式(Strategy Pattern)」,用於計算購物車的總金額,並允許 根據不同的定價策略(如正常價格或折扣價格) 來計算最終價格。

pricing_strategy_normal_discount_shopping_cart.py Sin formato
1from abc import ABC, abstractmethod
2
3# 策略介面
4class PricingStrategy(ABC):
5 @abstractmethod
6 def calculate_price(self, price):
7 pass
8
9# 具體策略類
10class NormalStrategy(PricingStrategy):
11 def calculate_price(self, price):
12 return price
13
14class 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# 上下文類
22class 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# 使用範例
34cart = ShoppingCart(NormalStrategy())
35items = [100, 200, 300]
36print("Total price with normal strategy:", cart.checkout(items)) # Output: Total price with normal strategy: 600
37
38cart.set_pricing_strategy(DiscountStrategy(0.2))
39print("Total price with discount strategy:", cart.checkout(items)) # Output: Total price with discount strategy: 480
40