Strategy Pattern 策略模式

来源:互联网 发布:python中九九乘法表 编辑:程序博客网 时间:2024/05/22 06:14

Design Principle:

Identify the aspects of your application that vary and separate them from what stays the same. 将变化的分离出来,封装变化。

Take what varies and "encapsulate" it so it won't affect the rest of the code.

Program to an interface/supertype, not an implementation. Use Supertype instead of concrete implementation. Assign the concrete implememtation object at runtime.针对超类编程,不对实现编程。

Favor composition over inheritance. 多用组合。

Change behavior at runtime.


Strategy Pattern: defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

策略模式定义一个抽象的算法接口,比如说排序算法(SortMethod interface, 其方法为sort())。然后用不同具体的算法implements这个统一的接口,就得到了具体的排序算法簇。

在使用这个算法的类中声明一个该算法接口的 reference,然后定义调用算法的方法和设置算法的方法。

策略组:

public interface SortMethod {public void sort(Object o);}public class MergeSort implements SortMethod {@Overridepublic void sort(Object o) {//Merge Sort}}public class InsertSort implements SortMethod {@Overridepublic void sort(Object o) {//Insert Sort}}
定义使用策略组的类:

public class MyCollection {private SortMethod sortMethod;public void runSort() {sortMethod.sort(this);}public void setSortMethod(SortMethod method){sortMethod = method;}}
动态定义使用的策略:

MyCollection mycol = new MyCollection();mycol.setMethod(new MergeSort());mycol.runSort();

策略模式实际是提供了一组可替换的行为/方法/算法,用户需要知道可用的策略有哪些,选用哪一个策略但不必关心策略的细节。用户在runtime可以动态改变使用的策略。当添加策略或者策略升级时,不必让用户改变其自身的代码。

因此:

1. 在系统中需要一种行为,而这种行为在多种类中要有不同(而也可在另一些类中有相同)的表现。使用策略模式,将这种行为抽象成接口,并以多种不同的具体实现。这样一个对象就可以在许多表现中动态选择。

2. 客户端必须知道所有的策略类,并自行决定使用哪一个策略类。这就意味着客户端必须理解这些算法的区别,以便适时选择恰当的算法类。换言之,策略模式只适用于客户端知道所有的算法或行为的情况。

应用;Duck Simulation (不同Duck有不同的fly方法和quack方法)


0 0