策略模式
定义了算法族,分别封装起来,让它们之间可以互相替换。此模式让算法的变化独立于使用算法的客户。
作为动态语言,Python实现策略模式非常容易,只要所有算法提供相同的函数即可。
import os
class Script:
def __init__(self, cmd):
self._cmd = cmd
def run_by(self, runner):
runner.run(self._cmd)
class Runner:
def run(self, cmd):
os.system(cmd)
class MockRunner:
def run(self, cmd):
print "Run", cmd
if __name__ == "__main__":
s = Script("echo test")
s.run_by(Runner())
s.run_by(MockRunner())
转载于:https://www.cnblogs.com/tuzkee/p/3741255.html
相关资源:详解Python设计模式之策略模式