策略模式定义:就是能够把一系列“可互换的”算法封装起来,并根据用户需求来选择其中一种。
**策略模式实现的核心就是:将算法的使用和算法的实现分离。**算法的实现交给策略类。算法的使用交给环境类,环境类会根据不同的情况选择合适的算法。
在使用策略模式的时候,需要了解所有的“策略”(strategy)之间的异同点,才能选择合适的“策略”进行调用。
class Stragegy():# 子类必须实现 interface 方法def interface(self):raise NotImplementedError()# 策略Aclass StragegyA():def interface(self):print("This is stragegy A")# 策略Bclass 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]();};// 调用策略Acontext("A");// 调用策略Bcontext("B");