Skip to content

策略模式

策略(Strategy)模式的定义:该模式定义了一系列算法,并将每个算法封装起来,使它们可以相互替换,且算法的变化不会影响使用算法的客户。策略模式属于对象行为模式,它通过对算法进行封装,把使用算法的责任和算法的实现分割开来,并委派给不同的对象对这些算法进行管理。

代码实现:

typescript
const Strategy = new Map([
  [
    "addItem",
    (data: string) => {
      return `The action is add,data:${data}`;
    },
  ],
  [
    "setItem",
    (data: string) => {
      return `The action is set,data:${data}`;
    },
  ],
  [
    "removeItem",
    (data: string) => {
      return `The action is remove,data:${data}`;
    },
  ],
]);

const context = (key: "addItem" | "setItem" | "removeItem", data: string) => {
  return Strategy.has(key) && Strategy.get(key)?.call(this, data);
};

const str = context("addItem", "hello world");