#coding: Utf-8 ' strategy mode: is the use of multiple algorithms to solve a problem, the most important feature is the ability to transparently switch the algorithm at runtime (client-side code is not aware of change) If there are two algorithms, one for a small amount of input effect, and the other for a lot of input, then you can use the policy mode at run time based on the input data to decide which algorithm to use to think or to cite an example: such as Monkey king hit the Devil, this is a real problem, is to play the monster this thing. so how to hit the monsters? That is, with what method to fight, with what tricks. encounter Bones Jing with golden cudgel to fight, encounter spider essence with fist that is encounter different monsters, take different play. But all of them are solving a problem, that is, to play the monster just based on the different objects to play different play "' #打法: Golden cudgel def golden_hoops (monster): #monster参数用于接收妖怪类型 return "Golden hoops ..." #打法: Fist def Fist (Monster): # monster parameter for receiving monster type return "Fist ..." # Select Strategy Def choose_strategy (monster, strategy): #monster参数用于接收妖怪类型 #strategy参数用于接收不同的打法 (that is, the corresponding function name) return strategy (monster) #逻辑控制def main (): while true:&Nbsp; monster = input ("enter the monster: ") #输入一个怪物 if monster == "quit": print ("Bye!!!") return strategy_option = none available_ strategy = {' 1 ':golden_hoops, ' 2 ':fist} #定义一个可用的战略 while strategy_option not in available_strategy.keys (): strategy_option = input ("Choose strategy [1] Use golden hoops, [2] Use fist : ") #战略选择 trY: final_ strategy = available_strategy[strategy_option] print ("play monster ({0}), using ({1}) Strategy ". Format (Monster, choose_strategy (monster, final_strategy)) #这是重点, according to different monsters using different strategies except KeyError: print ("No strategy options {} ". Format (available_strategy)) if __name__ == ' __main__ ': main () #OK! This is the end of the example, I hope friends can understand. I use this example to understand the thinking of the strategy model and apply it to the actual project
Python design pattern-strategy mode (Monkey King with what to play monsters)