Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

策略模式 #220

Open
louzhedong opened this issue Jun 16, 2020 · 0 comments
Open

策略模式 #220

louzhedong opened this issue Jun 16, 2020 · 0 comments

Comments

@louzhedong
Copy link
Owner

策略模式

定义一组算法,将每个算法都封装起来,并且使它们之间可以互换

优点:

算法可以自由切换

避免使用多重条件判断

扩展性良好

缺点:

策略类数量增多

所有的策略类都需要对外暴露

实现
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];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant