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

python实现策略模式

时间:2015-01-06 18:19:24      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:python   python教程   python视频   python培训   

策略模式如图所示:

技术分享

代码如下:
#!/usr/bin/env python
# -*- coding:utf-8 -*-

class Strategy:
    "抽象算法类"

    def algorithmInterface(self):
        "抽象方法"
        pass

class ConcreteStrategyA(Strategy):
    "具体算法类A"

    def algorithmInterface(self):
        "具体实现方法"

        print(‘Algorithm A‘)


class ConcreteStrategyB(Strategy):
    "具体算法类A"

    def algorithmInterface(self):
        "具体实现方法"

        print(‘Algorithm B‘)


class ConcreteStrategyC(Strategy):
    "具体算法类A"

    def algorithmInterface(self):
        "具体实现方法"

        print(‘Algorithm C‘)

class Context:
    "上下文类"

    def __init__(self, strategy):
        self.strategy = strategy

    def contextInterface(self):
        "上下文接口"

        self.strategy.algorithmInterface()

if __name__ == ‘__main__‘:
    "相同调用方法不同策略"

    context = Context(ConcreteStrategyA())
    context.contextInterface()

    context = Context(ConcreteStrategyB())
    context.contextInterface()

    context = Context(ConcreteStrategyC())
    context.contextInterface()


学习转载于:www.pythonfan.org

python实现策略模式

标签:python   python教程   python视频   python培训   

原文地址:http://pythonfan.blog.51cto.com/9764080/1599757

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