首页 > 编程 > Python > 正文

python优雅实现策略模式

2019-11-11 07:53:08
字体:
来源:转载
供稿:网友

优雅实现策略模式; 在awesome-python上有一个关于模式设计的包,对包中的代码做了一点修改。

# -*- coding: utf-8 -*-"""http://stackoverflow.com/questions/963965/how-is-this-strategy-pattern -written-in-python-the-sample-in-wikipediaIn most of other languages Strategy pattern is implemented via creating somebase strategy interface/abstract class and subclassing it with a number ofconcrete strategies (as we can see athttp://en.wikipedia.org/wiki/Strategy_pattern), however Python supportshigher-order functions and allows us to have only one class and injectfunctions into it's instances, as shown in this example."""import typesclass StrategyExample:    def __init__(self, func=None):        self.name = 'Strategy Example 0'        if func is not None:            self.select(func)    def __call__(self, arg=''):   # special method for execute        self.execute()    def execute(self):        PRint('nothing')    def select(self, func):        # the key of the pattern        self.execute = types.MethodType(func, self)    def make(self):        self.select(execute_replacement1)def execute_replacement1(obj):    print(obj.name + ' from execute 1')def execute_replacement2(obj):    print(obj.name + ' from execute 2')class SubStrategy(StrategyExample):    def __init__(self, func=None):        super(SubStrategy, self).__init__(func)        self.name = 'Strategy Example x'if __name__ == '__main__':    strat0 = StrategyExample()    stratx = SubStrategy()    stratx()    strat1 = StrategyExample(execute_replacement1)    strat1.name = 'Strategy Example 1'    strat2 = StrategyExample(execute_replacement2)    strat2.name = 'Strategy Example 2'    strat0()    strat1()    strat2()    strat2.select(execute_replacement1)    strat2()    stratx = SubStrategy(execute_replacement2)    stratx()

输出为

nothingnothingStrategy Example 1 from execute 1Strategy Example 2 from execute 2Strategy Example 2 from execute 1Strategy Example x from execute 2


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表