做者按:《天天一个设计模式》旨在初步领会设计模式的精髓,目前采用
javascript
(靠这吃饭)和python
(纯粹喜欢)两种语言实现。诚然,每种设计模式都有多种实现方式,但此小册只记录最直截了当的实现方式 :)javascript
策略模式定义:就是可以把一系列“可互换的”算法封装起来,并根据用户需求来选择其中一种。java
策略模式实现的核心就是:将算法的使用和算法的实现分离。算法的实现交给策略类。算法的使用交给环境类,环境类会根据不一样的状况选择合适的算法。python
在使用策略模式的时候,须要了解全部的“策略”(strategy)之间的异同点,才能选择合适的“策略”进行调用。git
class Stragegy(): # 子类必须实现 interface 方法 def interface(self): raise NotImplementedError() # 策略A class StragegyA(): def interface(self): print("This is stragegy A") # 策略B 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__": # 使用策略A的算法 cxt = Context( StragegyA ) cxt.interface() # 使用策略B的算法 cxt.update_stragegy( StragegyB ) cxt.interface()
// 策略类 const strategies = { A() { console.log("This is stragegy A"); }, B() { console.log("This is stragegy B"); } }; // 环境类 const context = name => { return strategies[name](); }; // 调用策略A context("A"); // 调用策略B context("B");