策略模式【strategy】
- 什么是策略模式
定义一系列的算法 ,把它们一个个封装起来 , 并且使它们可相互替换。本模式使得算法可独
立于使用它的客户而变化。别名政策(Policy) - 什么场景会用到命令模式
这个模式比较好理解,它充分的利用了抽象和多态,策略模式是一种定义了一系列算法的方法,从概念上来看,所有这些算法完成的都是相同的工作,只是实现不同,它可以以相同的方式调用所有的算法,减少了各种算法类与使用算法类之间的耦合。
我们来想想一下这个场景,我们最开始接触计算机编程的时候一定会学到排序,冒泡,快速,选择,归并排序,试着传入一个指定的数字集合,对它进行不同的排序,我们一定要从代码的可扩展行上面考虑
public interface SortingAlgorithm {
void sort(Collection collection);
}
public class BubbleSortAlgorithm implements SortingAlgorithm {
@Override
public void sort(Collection collection) {
System.out.println("Bubble Sort");
}
}
public class MergeSortAlgorithm implements SortingAlgorithm {
@Override
public void sort(Collection collection) {
System.out.println("Merge sort");
}
}
public class QuickSortAlgorithm implements SortingAlgorithm {
@Override
public void sort(Collection collection) {
System.out.println("Quick Sort");
}
}
public class SelectionSortAlgorithm implements SortingAlgorithm {
@Override
public void sort(Collection collection) {
System.out.println("Selection Sort");
}
}
public class Context {
private SortingAlgorithm sortingAlgorithm;
public void setSortingAlgorithm(
SortingAlgorithm sortingAlgorithm) {
this.sortingAlgorithm = sortingAlgorithm;
}
public void sort(Collection collection) {
sortingAlgorithm.sort(collection);
}
}
测试方法如下:
public static void main(String[] args) {
Context context = new Context();
context.setSortingAlgorithm(new QuickSortAlgorithm());
context.sort(Collections.emptyList());
context.setSortingAlgorithm(new BubbleSortAlgorithm());
context.sort(Collections.emptyList());
context.setSortingAlgorithm(new MergeSortAlgorithm());
context.sort(Collections.emptyList());
context.setSortingAlgorithm(new SelectionSortAlgorithm());
context.sort(Collections.emptyList());
}
- 适用性
当存在以下情况时使用strategy模式
• 许多相关的类仅仅是行为有异。“策略”提供了一种用多个行为中的一个行为来配置一
个类的方法。
• 需要使用一个算法的不同变体。例如,你可能会定义一些反映不同的空间 /时间权衡的
算法。当这些变体实现为一个算法的类层次时 [ H O 8 7 ] ,可以使用策略模式。
• 算法使用客户不应该知道的数据。可使用策略模式以避免暴露复杂的、与算法相关的数
据结构。
• 一个类定义了多种行为 , 并且这些行为在这个类的操作中以多个条件语句的形式出现。
将相关的条件分支移入它们各自的strategy类中以代替这些条件语句。
相关参考:
<大话设计模式>,<设计模式,可复用面向对象软件的基础>
源码在此