-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathstrategy_pattern.py
68 lines (50 loc) · 1.53 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
66
67
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'Andy'
'''
大话设计模式
设计模式——策略模式
策略模式(strategy):它定义了算法家族,分别封装起来,让他们之间可以相互替换,此模式让算法的变化,不会影响到使用算法的客户
'''
#现金收费抽象类
class CashSuper(object):
def accept_cash(self,money):
pass
#正常收费子类
class CashNormal(CashSuper):
def accept_cash(self,money):
return money
#打折收费子类
class CashRebate(CashSuper):
def __init__(self,discount=1):
self.discount = discount
def accept_cash(self,money):
return money * self.discount
#返利收费子类
class CashReturn(CashSuper):
def __init__(self,money_condition=0,money_return=0):
self.money_condition = money_condition
self.money_return = money_return
def accept_cash(self,money):
if money>=self.money_condition:
return money - (money / self.money_condition) * self.money_return
return money
#具体策略类
class Context(object):
def __init__(self,csuper):
self.csuper = csuper
def GetResult(self,money):
return self.csuper.accept_cash(money)
if __name__ == '__main__':
money = input("原价: ")
strategy = {}
strategy[1] = Context(CashNormal())
strategy[2] = Context(CashRebate(0.8))
strategy[3] = Context(CashReturn(100,10))
mode = input("选择折扣方式: 1) 原价 2) 8折 3) 满100减10: ")
if mode in strategy:
csuper = strategy[mode]
else:
print "不存在的折扣方式"
csuper = strategy[1]
print "需要支付: ",csuper.GetResult(money)