python设计模式第九天策略模式
Posted liuzhiqaingxyz
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python设计模式第九天策略模式相关的知识,希望对你有一定的参考价值。
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
以上是关于python设计模式第九天策略模式的主要内容,如果未能解决你的问题,请参考以下文章