策略模式

定义

定义一系列算法,把它们一个个封装起来,并且使它们可以相互替换,这使算法独立于客户变化而变化

实例



import types


class StrategyExample:

    def __init__(self, func=None):
        self.name = 'Strategy Example 0'
        if func is not None:
            self.execute = types.MethodType(func, self)

    def execute(self):
        print(self.name)


def execute_replacement1(self):
    print(self.name + ' from execute 1')


def execute_replacement2(self):
    print(self.name + ' from execute 2')


if __name__ == '__main__':
    strat0 = StrategyExample()

    strat1 = StrategyExample(execute_replacement1)
    strat1.name = 'Strategy Example 1'

    strat2 = StrategyExample(execute_replacement2)
    strat2.name = 'Strategy Example 2'

    strat0.execute()
    strat1.execute()
    strat2.execute()

### OUTPUT ###
# Strategy Example 0
# Strategy Example 1 from execute 1
# Strategy Example 2 from execute 2


execute_replacement1, execute_replacement2 是独立算法 StrategyExample 是可以让它们相互替换的平台。

注意types.MethodType的使用

adding-a-method-to-an-existing-object-instance 给 Python 已存在的类动态的添加方法

Loading Disqus comments...
Table of Contents