python优雅实现策略模式
来源:互联网 发布:淘宝买家仅退款不退货 编辑:程序博客网 时间:2024/06/07 10:27
优雅实现策略模式; 在awesome-python上有一个关于模式设计的包,对包中的代码做了一点修改。BaseStrateby最核心的方法是select.
# -*- 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 typesimport randomclass BaseStrategy: def __init__(self, func=None): if func is not None: self.select(func) def __call__(self, *args, **kwargs): self.execute(*args, **kwargs) def execute(self, *args, **kwargs): pass def select(self, func): # redefine a method self.execute = types.MethodType(func, self)class StrategyExample(BaseStrategy): def __init__(self, func=None): self.name = 'Strategy Example 0' if func is not None: self.select(func) def execute(self, arg='nothing'): print(arg) def make(self): self.select(execute_replacement1) def random(self): r = random.random() if r > 0.5: self.select(execute_replacement1) else: self.select(execute_replacement2)# strategiesdef execute_replacement1(obj, s=' from execute'): print(obj.name + s + '1')def execute_replacement2(obj, s=' from execute'): print(obj.name + s + '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() for k in range(5): stratx = SubStrategy() stratx.random() stratx('shit')### OUTPUT #### nothing# nothing# Strategy Example 1 from execute 1# Strategy Example 2 from execute 2# Strategy Example 2 from execute 1# Strategy Example xshit# Strategy Example xshit# Strategy Example xshit# Strategy Example xshit# Strategy Example xshit
0 0
- python优雅实现策略模式
- 设计模式--策略模式的python实现
- python优雅实现适配器
- 设计模式之策略模式(python实现)
- 设计模式二(策略模式,采用python实现)
- python的策略模式
- 策略模式(python)
- Python设计模式-策略模式
- python设计模式(策略模式)
- Python设计模式--策略模式
- 策略模式的实现
- 策略模式C++实现
- 策略模式的实现
- 策略模式实现
- c++ 实现策略模式
- 策略模式c++实现
- JS实现策略模式
- C++实现策略模式
- ℃江让您从精通到入门:第一次
- HDU1698 Just a Hook 线段树成段替换
- java设计模式之组合模式
- tcp为什么需要3次握手和3次握手的过程
- dfs走迷宫
- python优雅实现策略模式
- Sticks --dfs 剪枝
- java编程思想读书笔记--第四章 控制执行流程
- 用穷举法解决皇后问题
- Android 热修复 Tinker接入及源码浅析
- 反转单词顺序
- #21. DFA
- 用CSS画出三角形
- 写一个 iOS 复杂表单的正确姿势