策略模式 定义算法簇,分别封装起来, 让他们之间可以互相替换,此模式让算法的变化对立与使用算法的客户
#coding:utf-8
class Duck:
def __init__(self):
self.fly_behavior = FlyNoWay()
# 把飞的动作托付给FlyBehavior对象的子类
def perform_fly(self):
self.fly_behavior.fly()
def set_fly_behavior(self, fly_behavior):
self.fly_behavior = fly_behavior
# 不同的飞翔方法,都继承FlyBehavior
class FlyBehavior:
def fly(self):
raise NotImplemented()
class FlyWithWings(FlyBehavior):
def fly(self):
print 'fly with wings'
class FlyNoWay(FlyBehavior):
def fly(self):
print 'can not fly'
if __name__ == '__main__':
d=Duck()
d.perform_fly() #can not fly
d.set_fly_behavior(FlyWithWings())
d.perform_fly() #fly with wings