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

策略模式 #461

Open
LittlebearHat opened this issue Feb 11, 2023 · 0 comments
Open

策略模式 #461

LittlebearHat opened this issue Feb 11, 2023 · 0 comments

Comments

@LittlebearHat
Copy link
Contributor

方案一:JS对象写法

let strategies = {
  add: function (num) {
    return num + num;
  },
  multiply: function (num) {
    return num * num;
  },
};
let calculateBonus = function (strategy, num) {
  return strategies[strategy](num);
};
console.log(calculateBonus("add", 3));
console.log(calculateBonus("multiply", 3));

方案二:传统写法

class Strategies {}
class Add extends Strategies {
  start(num) {
    return num + num;
  }
}
class Multiply extends Strategies {
  start(num) {
    return num * num;
  }
}
class Context {
  constructor(strategy) {
    this.strategy = strategy;
  }
  start(num) {
    return this.strategy.start(num);
  }
}
let context = new Context(new Add());
console.log(context.start(3));
context = new Context(new Multiply());
console.log(context.start(3));
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