策略模式定义了算法族,分别封装起来,让它们之间可以互相替换,此模式使算法的变化独立于使用算法的客户。
python实现:
"""
策略模式
"""
class Duck(object):
def __init__(self, fly, quack):
self.fly = fly
self.quack = quack
def perform_quack(self):
self.quack.quack()
def perform_fly(self):
self.fly.fly()
def display(self):
raise NotImplementedError()
def swim(self):
print("all ducks float, even decoys")
class MallarDuck(Duck):
def display(self):
print("this is a real Mallard duck")
class FlyBehavior(object):
def fly(self):
raise NotImplementedError()
class FlyWithWings(FlyBehavior):
def fly(self):
print("I'm flying")
class FlyNoway(FlyBehavior):
def fly(self):
print("I'm can't fly")
class QuckBehavior(object):
def quack(self):
raise NotImplementedError()
class Quack(QuckBehavior):
def quack(self):
print("Quack")
class Squeak(QuckBehavior):
def quack(self):
print("Squeak")
if __name__ == "__main__":
fly = FlyWithWings()
quack = Squeak()
mallard = MallarDuck(fly, quack)
mallard.perform_fly()
mallard.perform_quack()
本文介绍了策略模式的概念,该模式允许将算法封装为独立的对象,以便在运行时进行替换和选择。通过一个具体的Python实现案例,展示了如何使用策略模式来实现鸭子的行为变化,包括飞行和叫声的不同实现。
1444

被折叠的 条评论
为什么被折叠?



