策略模式

# 策略模式

定义一些列算法, 并将每种算法分别放入独立的类中, 使算法的对象能够相互替换.

通俗来讲

类比

# 优点

  • 可以在运行时切换对象内的算法.

  • 可以将算法的实现和使用算法的代码隔离开来.

  • 可以使用组合来代替继承.

  • 开闭原则: 无需对上下文进行修改就能够引入新的策略

# 缺点

  • 如果算法极少发生改变, 那么没有任何理由引入新的类和接口. 使用该模式只会让程序过于复杂.

  • 客户端必须知晓策略间的不同 —— 它需要选择合适的策略

  • 许多现代编程语言支持函数类型功能, 允许你在一组匿名函数中实现不同版本的算法. 这样, 使用这些函数的方式就和使用策略对象时完全相同, 无需借助额外的类和接口来保持代码简洁.

# 适用场景

  • 使用对象中各种不同的算法变体, 并希望能在运行时切换算法时

  • 有许多仅在执行某些行为时略有不同的相似类时

  • 如果算法在上下文的逻辑中不是特别重要, 使用该模式能将类的业务逻辑与其算法实现细节隔离开来

  • 当类中使用了复杂条件运算符以在同一算法的不同变体中切换时

# 实现

点击查看代码
interface Strategy {
  doAlgorithm(data: string[]): string[];
}

/**
 * The Context defines the interface of interest to clients.
 */
class StrategyContext {
  private strategy: Strategy;

  constructor(strategy: Strategy) {
    this.strategy = strategy;
  }

  public setStrategy(strategy: Strategy) {
    this.strategy = strategy;
  }

  public doSomeBusinessLogic() {
    console.log(`Context: Sorting data using the strategy (not sure how it'll do it)`);
    const result = this.strategy.doAlgorithm(['a', 'b', 'c', 'd', 'e']);
    console.log(result.join(','));
  }
}

class ConcreteStrategyA implements Strategy {
  public doAlgorithm(data: string[]): string[] {
    return data.sort();
  }
}

class ConcreteStrategyB implements Strategy {
  public doAlgorithm(data: string[]): string[] {
    return data.reverse();
  }
}

const contextInstance = new StrategyContext(new ConcreteStrategyA());
console.log(`Client: Strategy is set to normal sorting.`);
contextInstance.doSomeBusinessLogic();

console.log('');

console.log(`Client: Strategy is set to reverse sorting.`);
contextInstance.setStrategy(new ConcreteStrategyB());
contextInstance.doSomeBusinessLogic();

// output:
// Client: Strategy is set to normal sorting.
// Context: Sorting data using the strategy (not sure how it'll do it)
// a, b, c, d, e

// Client: Strategy is set to reverse sorting.
// Context: Sorting data using the strategy (not sure how it'll do it)
// e, d, c, b, a
 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57