美文网首页
3.设计模式(策略模式)

3.设计模式(策略模式)

作者: 悠哈121 | 来源:发表于2020-11-05 15:48 被阅读0次

    1.策略模式:第一部分是一组策略类,策略类封装了具体的算法,并负责具体的计算过程。第二部分是环境类Context,Context接受客户的请求,随后把请求委托给某一个策略类。Context中要维持对某个策略对象的引用

    代码示例
    //计算奖金:绩效为S:年终奖为基本工资4倍,绩效为A:年终奖为三倍,绩效为B:年终奖为2倍
    //奖金计算规则
    var PS = function(){}
    PS.prototype.calcFun = function(money){
      return money * 4
    }
    var PA = function(){}
    PA.prototype.calcFun = function(money){
      return money * 3
    }
    var PB = function(){}
    PB.prototype.calcFun = function(money){
      return money * 2
    }
    //奖金类
    var Bonus = function(){
      this.salary = null; //原始工资
      this.strategy = null; //绩效对象的策略对象
    }
    Bonus.prototype.setSalary=function(money){
      this.salary = money;
    }
    Bonus.prototype.setStrategy = function(strategy){
      this.strategy = strategy;
    }
    Bonus.prototype.getBonus = function(){
      return this.strategy.calcFun(this.salary)
    }
    var bonus = new Bonus(); 
    bonus.setSalary( 10000 ); 
    bonus.setStrategy( new PS() ); // 设置策略对象
    console.log( bonus.getBonus() );
    JS策略模式实现
    //奖金计算规则
    var P = {
      "S":function(money){
        return money * 4
      },
      "A":function(money){
        return money * 3
      },
      "B":function(money){
        return money * 2
      }
    }
    function calcFun(type,money){
      return P[type](money)
    }
    console.log(calcFun("S",1000))
    

    相关文章

      网友评论

          本文标题:3.设计模式(策略模式)

          本文链接:https://www.haomeiwen.com/subject/koaovktx.html