1. 策略模式
分类:行为型模式
关键点: 在策略模式(Strategy Pattern)中,一个类的行为或其算法可以在运行时更改。
2. 任务
实现内容:
到达目的地有多种方案:步行、开车。。。步行成本低但耗时长,开车成本高有时短,请用代码实现这个逻辑
3. JS 实现
3.1. 任务一:
class StrategyPedestrianism {
constructor() {
this.timeCost = 100;
this.MoneyCost = 1;
}
}
StrategyPedestrianism.prototype.getCost = function () {
return this.timeCost + this.MoneyCost;
};
class StrategyBike {
constructor() {
this.timeCost = 50;
this.MoneyCost = 500;
}
}
StrategyBike.prototype.getCost = function () {
return this.timeCost + this.MoneyCost;
};
class StrategyCar {
constructor() {
this.timeCost = 10;
this.MoneyCost = 1000;
}
}
StrategyCar.prototype.getCost = function () {
return this.timeCost + this.MoneyCost;
};
class Context {
constructor(strategy) {
this._strategy = strategy;
}
}
Context.prototype.getCost = function () {
return this._strategy.getCost();
};
let context = new Context(new StrategyCar());
console.log(context.getCost());
3.2. 任务二:
let strategys = {
StrategyPedestrianism:{
timeCost:100,
MoneyCost:1,
getCost:function () {
return this.timeCost + this.MoneyCost;
}
},
StrategyBike:{
timeCost:50,
MoneyCost:100,
getCost:function () {
return this.timeCost + this.MoneyCost;
}
},
StrategyCar:{
timeCost:10,
MoneyCost:1000,
getCost:function () {
return this.timeCost + this.MoneyCost;
}
}
}
let context = {
getCost:function(strategyName){
return strategys[strategyName].getCost()
}
}
console.log(context.getCost('StrategyCar'));