JS设计模式-03-策略模式

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'));


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值