-
Notifications
You must be signed in to change notification settings - Fork 0
/
strategy_pattern.py
65 lines (44 loc) · 1.61 KB
/
strategy_pattern.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
from dataclasses import dataclass, field
from abc import abstractmethod, ABC
@dataclass
class Item:
name: str
price: int
class ShippingStrategy(ABC):
@abstractmethod
def calculate(self, items_cost: int) -> int:
pass
class ShippingStandard(ShippingStrategy):
def calculate(self, items_cost: int) -> int:
if items_cost <= 50:
return 5
elif items_cost > 50:
return 0
class ShippingExpress(ShippingStrategy):
def calculate(self, items_cost: int) -> int:
if items_cost <= 50:
return 10
elif items_cost > 50:
return 5
class ShippingOvernight(ShippingStrategy):
def calculate(self, _: int) -> int:
return 50
@dataclass
class ShoppingCart:
items: list[Item] = field(default_factory=list)
def add_item(self, item: Item) -> None:
self.items.append(item)
def calculate_total_cost(self, shipping_strategy: ShippingStrategy) -> int:
items_cost = sum(item.price for item in self.items)
shipping_cost = shipping_strategy.calculate(items_cost)
return items_cost + shipping_cost
def main() -> None:
shopping_cart = ShoppingCart()
shopping_cart.add_item(Item(name="laptop", price=1500))
shopping_cart.add_item(Item(name="mouse", price=30))
shopping_cart.add_item(Item(name="keyboard", price=40))
print(shopping_cart.calculate_total_cost(ShippingStandard()))
print(shopping_cart.calculate_total_cost(ShippingExpress()))
print(shopping_cart.calculate_total_cost(ShippingOvernight()))
if __name__ == "__main__":
main()