一:模式用途
![](https://i-blog.csdnimg.cn/blog_migrate/73f4589344354619c4a7d729fe5acd09.png)
策略模式:他定义了算法家族,分别封装起来,让他们之间可以互相替换,此模式让算法的变化,不会影响到使用算法的客户。不同的时间应用不同的业务规则就可以用这个模型。
class CashSuper:
def AcceptCash(self,money):
return 0
class CashNormal(CashSuper):
def AcceptCash(self,money):
return money
class CashRebate(CashSuper):
discount = 0
def __init__(self,ds):
self.discount = ds
def AcceptCash(self,money):
return money * self.discount
class CashReturn(CashSuper):
total = 0;
ret = 0;
def __init__(self,t,r):
self.total = t
self.ret = r
def AcceptCash(self,money):
if (money>=self.total):
return money - self.ret
else:
return money
class CashContext:
def __init__(self,csuper):
self.cs = csuper
def GetResult(self,money):
return self.cs.AcceptCash(money)
if __name__ == "__main__":
money = input("money:")
strategy = {}
strategy[1] = CashContext(CashNormal())
strategy[2] = CashContext(CashRebate(0.8))
strategy[3] = CashContext(CashReturn(300,100))
ctype = input("type:[1]for normal,[2]for 80% discount [3]for 300 -100.")
if ctype in strategy:
cc = strategy[ctype]
else:
print ("Undefine type.Use normal mode.")
cc = strategy[1]
print ("you will pay:%d" %(cc.GetResult(money)))
可以看到策略类实现实例化出所有的可能,这样做就有点费事了,可以结合之前的工厂模式,
根据不同的需要实例化对应的类就好。