标签:str method imp 平滑 ace bubuko object pytho 模式
1. 定义
对一系列算法进行封装,为所有算法定义一个抽象的算法接口,可以平滑的进行算法切换
2. 策略模式的UML图
3.代码实现
#!/usr/bin/env python #! _*_ coding:UTF-8 _*_ from abc import ABCMeta, abstractmethod class Context(object): def setStrategy(self, strategy): self.__strategy = strategy def operation(self): self.__strategy.algorithmInterface() class Strategy(object): @abstractmethod def algorithmInterface(self): pass class ConcreteStrategyA(Strategy): def algorithmInterface(self): print "strategy A" class ConcreteStrategyB(Strategy): def algorithmInterface(self): print "strategy B" if __name__ == "__main__": context = Context() concreteStrategyA = ConcreteStrategyA() concreteStrategyB = ConcreteStrategyB() context.setStrategy(concreteStrategyA) context.operation() context.setStrategy(concreteStrategyB) context.operation()
结果:
/Users/liudaoqiang/PycharmProjects/numpy/venv/bin/python /Users/liudaoqiang/Project/python_project/day09_strategy/strategy_test.py
strategy A
strategy B
Process finished with exit code 0
标签:str method imp 平滑 ace bubuko object pytho 模式
原文地址:https://www.cnblogs.com/liuzhiqaingxyz/p/9490300.html