策略模式简单说和小时候我们玩的玩具差不多,一堆零部件通过不同的拼凑构成几个不同的机器人。
1.举个栗子
我们买了一个机器人,同时这个机器人配了三把武器,三把武器可以替换使用
2.Show in Code
在实例中,我们先创造一个人,天生自带人手
class People: def __init__(self, hand = None): self.name = "人手" if hand is not None: self.execute = types.MethodType(hand, self) def execute(self): #安装部件的位置 print(self.name)
现在我们再给他创建两个备用的手,一个pighand
、一个cathand
//创造猪手def pighand(self): print(self.name + " 用猪手") print("拱你")//创造猫爪def cathand(self): print(self.name + " 用猫爪") print("抓你")
3.完整代码
import types//创造一个人class People: def __init__(self, hand = None): self.name = "人手" if hand is not None: self.execute = types.MethodType(hand, self) def execute(self): #安装部件的位置 print(self.name)//创造猪手def pighand(self): print(self.name + " 用猪手") print("拱你")//创造猫爪def cathand(self): print(self.name + " 用猫爪") print("抓你")if __name__ == '__main__': hand0 = People() #用猪手替换人手 hand1 = People(pighand) hand1.name = "猪手" #用猫爪替换ren'hsou hand2 = People(cathand) hand2.name = "猫爪" hand0.execute() hand1.execute() hand2.execute()
4.总结
将相同提取,将变化拆分