这篇文章主要帮助大家轻松掌握 python 设计模式之策略模式, 具有一定的参考价值,感兴趣的小伙伴们可以参考一下
Python 是一种面向对象、解释型计算机程序设计语言,由 Guido van Rossum 于 1989 年底发明,第一个公开发行版发行于 1991 年。Python 语法简洁而清晰,具有丰富和强大的类库。它常被昵称为胶水语言,它能够把用其他语言制作的各种模块(尤其是 C/C++)很轻松地联结在一起。
- """
- 策略模式
- """
- import types
- class StrategyExample:
- def __init__(self, func=None):
- self.name = '策略例子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 + ' 从执行1')
- def execute_replacement2(self):
- print(self.name + ' 从执行2')
- if __name__ == '__main__':
- strat0 = StrategyExample()
- strat1 = StrategyExample(execute_replacement1)
- strat1.name = '策略例子1'
- strat2 = StrategyExample(execute_replacement2)
- strat2.name = '策略例子2'
- strat0.execute()
- strat1.execute()
- strat2.execute()
运行结果如图:
来源: http://www.phperz.com/article/17/0316/310761.html