策略模式
louzhedong opened this issue · comments
Miracle commented
策略模式
定义一组算法,将每个算法都封装起来,并且使它们之间可以互换
优点:
算法可以自由切换
避免使用多重条件判断
扩展性良好
缺点:
策略类数量增多
所有的策略类都需要对外暴露
实现
Java
/**
* 策略接口
**/
public interface Strategy {
void doSomething();
}
/**
* 具体策略类
**/
public class ConcreteStrategy implements Strategy {
@Override
public void doSomething() {
}
}
/**
* 执行类
**/
public class Context {
private Strategy strategy = null;
public Context(Strategy _strategy) {
this.strategy = _strategy;
}
public void doAnything() {
this.strategy.doSomething();
}
}
/**
* 场景类
**/
public class Client {
public static void main(String[] args) {
Strategy strategy = new ConcreteStrategy();
Context context = new Context(strategy);
context.doAnything();
}
}
JavaScript
var strategies = {
"S": function (salary) {
return salary * 4;
},
"A": function (salary) {
return salary * 3;
},
"B": function (salary) {
return salary * 2;
}
}
var calculateBonus = function (level, salary) {
return strategies[level][salary];
}