码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-08-16 22:30:32      阅读:256      评论:0      收藏:0      [点我收藏+]

标签: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

 

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

标签:str   method   imp   平滑   ace   bubuko   object   pytho   模式   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!