python策略模式_设计模式(python实现):策略模式
策略模式簡單說和小時候我們玩的玩具差不多,一堆零部件通過不同的拼湊構(gòu)成幾個不同的機(jī)器人。
1.舉個栗子
我們買了一個機(jī)器人,同時這個機(jī)器人配了三把武器,三把武器可以替換使用
2.Show in Code
在實(shí)例中,我們先創(chuàng)造一個人,天生自帶人手
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)
現(xiàn)在我們再給他創(chuàng)建兩個備用的手,一個pighand、一個cathand
//創(chuàng)造豬手
def pighand(self):
print(self.name + " 用豬手")
print("拱你")
//創(chuàng)造貓爪
def cathand(self):
print(self.name + " 用貓爪")
print("抓你")
3.完整代碼
import types
//創(chuàng)造一個人
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)
//創(chuàng)造豬手
def pighand(self):
print(self.name + " 用豬手")
print("拱你")
//創(chuàng)造貓爪
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.總結(jié)
將相同提取,將變化拆分
總結(jié)
以上是生活随笔為你收集整理的python策略模式_设计模式(python实现):策略模式的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python类属性描述_如何描述Pyth
- 下一篇: opencv 人脸识别_人工智能-Ope