策略模式如圖所示:
代碼如下:
#!/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