首页 > 编程语言 > 详细

python设计模式第九天【策略模式】

时间:2018-08-16 22:10:47      阅读:230      评论:0      收藏:0      [点我收藏+]

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设计模式第九天【策略模式】

原文:https://www.cnblogs.com/liuzhiqaingxyz/p/9490300.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!