Dernière activité 10 months ago

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

timmy a révisé ce gist 10 months ago. Aller à la révision

Aucun changement

timmy a révisé ce gist 10 months ago. Aller à la révision

Aucun changement

timmy a révisé ce gist 1 year ago. Aller à la révision

1 file changed, 39 insertions

pricing_strategy_normal_discount_shopping_cart.py(fichier créé)

@@ -0,0 +1,39 @@
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
Plus récent Plus ancien