1. 什么是策略模式?
策略模式定义:就是能够把一系列“可互换的”算法封装起来,并根据用户需求来选择其中一种。
策略模式实现的核心就是:将算法的使用和算法的实现分离。算法的实现交给策略类。算法的使用交给环境类,环境类会根据不同的情况选择合适的算法。
2. 策略模式优缺点
在使用策略模式的时候,需要了解所有的“策略”(strategy)之间的异同点,才能选择合适的“策略”进行调用。
3. 代码实现
3.1 python3 实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| class Stragegy(): def interface(self): raise NotImplementedError()
class StragegyA(): def interface(self): print("This is stragegy A")
class StragegyB(): def interface(self): print("This is stragegy B")
class Context(): def __init__(self, stragegy): self.__stragegy = stragegy()
def update_stragegy(self, stragegy): self.__stragegy = stragegy()
def interface(self): return self.__stragegy.interface()
if __name__ == "__main__": cxt = Context( StragegyA ) cxt.interface()
cxt.update_stragegy( StragegyB ) cxt.interface()
|
3.2 javascript 实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| const strategies = { A() { console.log('This is stragegy A') }, B() { console.log('This is stragegy B') }, }
const context = (name) => { return strategies[name]() }
context('A')
context('B')
|
4. 参考