Policy mode (strategy pattern): It defines the algorithm family, respectively encapsulated, so that they can replace each other, this mode allows the algorithm changes, will not affect the use of the algorithm of the customer.
Here is the realization of a mall activity
1 #!/usr/bin/env python2 #-*-coding:utf-8-*-3 4 __author__='Andy'5 " "6 Liar design Mode7 design Pattern--Strategy mode8 policy mode (strategy): It defines the algorithm family, individually encapsulated, so that they can replace each other, this mode allows the algorithm to change, does not affect the use of the algorithm of the customer9 " "Ten One #Cash charges abstract class A classCashsuper (object): - - defAccept_cash (Self,money): the Pass - #Normal fee sub-category - classCashnormal (cashsuper): - + defAccept_cash (Self,money): - return Money + A #Discounted charges sub-category at classcashrebate (cashsuper): - - def __init__(self,discount=1): -Self.discount =Discount - - defAccept_cash (Self,money): in returnMoney *Self.discount - to #Rebate Fees sub-category + classCashreturn (cashsuper): - the def __init__(self,money_condition=0,money_return=0): *Self.money_condition =money_condition $Self.money_return =Money_returnPanax Notoginseng - defAccept_cash (Self,money): the ifmoney>=self.money_condition: + returnMoney-(money/self.money_condition) *Self.money_return A return Money the + #Specific policy Classes - classContext (object): $ $ def __init__(self,csuper): -Self.csuper =Csuper - the defGetResult (Self,money): - returnSelf.csuper.accept_cash (Money)Wuyi the - Wu - if __name__=='__main__': AboutMoney = input ("Original Price:") $Strategy = {} -STRATEGY[1] =Context (Cashnormal ()) -STRATEGY[2] = Context (Cashrebate (0.8)) -STRATEGY[3] = Context (Cashreturn (100,10)) Amode = input ("Select the Discount method: 1) Original price 2) 80 percent 3) full 100 minus Ten:") + ifModeinchstrategy: theCsuper =Strategy[mode] - Else: $ Print "non-existent discount methods" theCsuper = strategy[1] the Print "Payment Required:", Csuper. GetResult (Money)
The design of these classes is as follows:
Using a policy class Cashsuper define the common interface of the required algorithm, define three specific policy classes: Cashnormal,cashrebate,cashreturn, inherit from Cashsuper, define a context management class, receive a policy, And according to this strategy, when the need to change the policy, only need to pass in the instance when the different policies can be, eliminate the trouble of modifying the class
Big talk involves pattern Python implementation-policy mode