-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomposite.py
More file actions
71 lines (52 loc) · 1.65 KB
/
composite.py
File metadata and controls
71 lines (52 loc) · 1.65 KB
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
66
67
68
69
70
71
class Discount:
def price_after_discount(self, product):
return product.price
class PercentDiscount:
def __init__(self, discount, pct):
self.pct = pct
self.discount = discount
def price_after_discount(self, product):
baseprice = self.discount.price_after_discount(product)
return baseprice * (1 - self.pct)
class BuyXGetY:
def __init__(self, discount, minprice, reduction):
self.discount = discount
self.minprice = minprice
self.reduction = reduction
def price_after_discount(self, product):
baseprice = self.discount.price_after_discount(product)
if baseprice > self.minprice:
return baseprice - self.reduction
else:
return baseprice
class ShoppingCart:
def __init__(self, products):
self.products = products
def price(self):
return sum([x.price for x in self.products])
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
def add_discount(self, discount):
self.price = discount.price_after_discount(self)
class Bundle:
def __init__(self, products):
self.price = sum([x.price for x in products])
def add_discount(self, discount):
self.price = discount.price_after_discount(self)
iPhoneDeal = Bundle([
Product('iPhone', 750),
Product('iPhone case', 20),
Bundle([
Product('Support', 50),
Product('Cool Apps', 20),
])
])
discount = PercentDiscount(BuyXGetY(Discount(), 20, 10), 0.5)
iPhoneDeal.add_discount(discount)
s = ShoppingCart([
iPhoneDeal,
Product('Galaxy', 550),
])
print(s.price())