43e2 发表于 2015-1-7 08:21:01

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()



页: [1]
查看完整版本: python实现策略模式