将案例转换为战略模式

时间:2016-12-09 04:30:17

标签: javascript switch-statement strategy-pattern

Menu.prototype.iconMapping = function (_setroot){
  var case_root = _setroot;
  switch(case_root){
    case "type1":
      // function();
    break;
    case "type2":
     // function();
    break;
    case "type3":
     // function();
    break;
    case "type4":
     // function();
    break;
    case "type5":
     // function();
    break;
  }
}

使用JS设计模式有更好的方法吗?因为我听说switch/case有很多问题。你们能给我一些建议或告诉我实际应该怎么做吗?我听说策略模式可能适合这个,但我不知道从哪里开始。

2 个答案:

答案 0 :(得分:1)

一种解决方案可能是:

var funcs =
{
  'type1': function() { alert('one'  ); },
  'type2': function() { alert('two'  ); },
  'type3': function() { alert('three'); }
};

case_root = 'type2'; //demo
funcs.hasOwnProperty(case_root) && funcs[case_root]();

答案 1 :(得分:0)

这里https://dev.to/carlillo/design-patterns---strategy-pattern-in-javascript-2hg3

   class StratergyManager {
    constructor() {
        this._strategy= null
    }
    set strategy(strategy){
        this._strategy = strategy;
    }
    get strategy(){
        return this._strategy;
    }
    doAction () {
        this._strategy.doAction();
    }
}

class Stratergy1 {
    doAction () {
        console.log('Stratergy1')
    }
}

class Stratergy2 {
    doAction () {
        console.log('Stratergy2')
    }
}


const stratergyManager = new StratergyManager();
const stratergy1 = new Stratergy1();
const stratergy2 = new Stratergy2();

stratergyManager.strategy = stratergy1;
stratergyManager.doAction();

stratergyManager.strategy = stratergy2;
stratergyManager.doAction();