// 定义排序策略接口
interface SortStrategy {
sort(array: number[]): number[];
}
// 升序排序类
class AscendingSort implements SortStrategy {
sort(array: number[]): number[] {
return array.slice().sort((a, b) => a - b);
}
}
// 降序排序类
class DescendingSort implements SortStrategy {
sort(array: number[]): number[] {
return array.slice().sort((a, b) => b - a);
}
}
// Sorter类
class Sorter {
private strategy: SortStrategy;
constructor(strategy: SortStrategy) {
this.strategy = strategy;
}
executeSort(array: number[]): number[] {
return this.strategy.sort(array);
}
}
// 使用示例
const numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
const ascendingSorter = new Sorter(new AscendingSort());
const ascendingResult = ascendingSorter.executeSort(numbers);
console.log("升序结果:", ascendingResult);
const descendingSorter = new Sorter(new DescendingSort());
const descendingResult = descendingSorter.executeSort(numbers);
console.log("降序结果:", descendingResult);
这样设计的优势
- 可维护性:不同的排序策略被封装在各自的类中,修改某个排序策略的实现不会影响到其他策略和使用排序策略的代码。例如,如果要优化升序排序算法,只需修改
AscendingSort
类中的 sort
方法,而 Sorter
类和 DescendingSort
类的代码无需变动。
- 可扩展性:添加新的排序策略变得非常容易。只需要创建一个新的类实现
SortStrategy
接口,然后就可以在 Sorter
类中使用。例如,如果要添加一个按照数字平方值升序排序的策略,只需要创建一个新类实现 sort
方法,然后就可以在 Sorter
类中使用这个新策略。
- 灵活性:
Sorter
类不关心具体的排序逻辑,只依赖于 SortStrategy
接口。这使得在运行时可以根据不同的需求选择不同的排序策略。例如,在一个数据处理系统中,根据用户的不同选择动态切换升序或降序排序。
- 代码复用:
Sorter
类的 executeSort
方法可以复用,无论使用哪种排序策略,都可以通过 Sorter
类来调用排序方法,避免了重复编写排序调用的代码。