0. 项目地点
作者按:《天天一个设想形式》旨在开端体会设想形式的精华,现在采纳
javascript
(
靠这用饭)和
python
(
地道喜好)两种言语完成。固然,每种设想形式都有多种完成体式格局,但此小册只纪录最直接了当的完成体式格局 :)
1. 什么是战略形式?
战略形式定义:就是可以把一系列“可交换的”算法封装起来,并依据用户需求来挑选个中一种。
战略形式完成的中心就是:将算法的运用和算法的完成星散。算法的完成交给战略类。算法的运用交给环境类,环境类会依据差别的状况挑选适宜的算法。
2. 战略形式优缺点
在运用战略形式的时刻,须要相识一切的“战略”(strategy)之间的异同点,才挑选适宜的“战略”举行挪用。
3. 代码完成
3.1 python3完成
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()
3.2 javascript完成
// 战略类
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");
4. 参考
- 战略形式-Python四种完成体式格局
- Python设想形式 – 战略形式
- 《JavaScript设想形式和开辟实践》