策略模式簡單說和小時候咱們玩的玩具差很少,一堆零部件經過不一樣的拼湊構成幾個不一樣的機器人。python
咱們買了一個機器人,同時這個機器人配了三把武器,三把武器能夠替換使用code
在實例中,咱們先創造一我的,天生自帶人手it
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
class
//創造豬手 def pighand(self): print(self.name + " 用豬手") print("拱你") //創造貓爪 def cathand(self): print(self.name + " 用貓爪") print("抓你")
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()
將相同提取,將變化拆分import