1.描述
定义一系列算法,把他们一个个封装起来,并且使他们可以交互替换。本模式可以使算法独立于使用它的用户而变化。
2.优点
·上下文(Context)和具体策略(ConcreteStrategy)是松耦合关系。
·策略模式满足“开闭原则”。
3.用途
·一个类定义了多种行为,并且这些行为在这个方法中以多个条件形式的语句出现,可以使用策略模式避免在类中大量使用条件语句。
·程序不希望暴露复杂的、与算法相关的数据结构。
·使用一个方法的不同变体。(要和重载区分)
4.模式使用
·策略(Strategy):策略是一个接口,该接口定义若干个算法标识,即定义了若干个抽象方法。
·具体策略(ConcreteStrategy):具体策略是实现策略接口的类。具体策略实现策略接口所定义的抽象方法,即给出算法标识的具体算法。
·上下文(Context):上下文是依赖于策略接口的类,即上下文包含有策略声明的变量。上下文中提供一个方法,该方法委托策略变量调用具体策略所实现的策略接口中的具体方法。
5.UML图
6.案例
Game类中有一个计算平均分的方法getScore(double[] a),对于Game类的对象,有些要求getScore(double[] a)方法计算算数平均值,有些要求getScore(double[] a)方法计算几何平均值。(显然不能使用重载)
1 package 策略模式; 2 3 public class test1 { 4 public static void main(String[] args) { 5 double[] a = new double[10]; 6 for(int i = 0; i < 10; i++) 7 a[i] = Math.random() * 100; 8 Game game = new Game(new Strategy1()); //策略1 算术平均值 9 System.out.println("策略1 算术平均值" + game.getScore(a)); 10 game = new Game(new Strategy2()); //策略2 几何平均值 11 System.out.println("策略2 几何平均值" + game.getScore(a)); 12 } 13 14 } 15 16 /* 17 * 策略 18 */ 19 interface ComputableStrategy{ 20 public abstract double ComputeScore(double[] a); 21 } 22 23 /* 24 * 具体策略 计算算数平均值 25 */ 26 class Strategy1 implements ComputableStrategy{ 27 28 public double ComputeScore(double[] a) { 29 double score = 0 , sum = 0; 30 for(int i = 0; i < a.length; i++) 31 sum = sum + a[i]; 32 score = sum/a.length; 33 return score; 34 } 35 36 } 37 38 /* 39 * 具体策略 计算几何平均值 40 */ 41 class Strategy2 implements ComputableStrategy{ 42 43 public double ComputeScore(double[] a) { 44 double score = 0 , multi = 1; 45 for(int i = 0; i < a.length; i++) 46 multi = multi * a[i]; 47 score = Math.pow(multi, 1.0/a.length); 48 return score; 49 } 50 51 } 52 53 /* 54 * 上下文 55 */ 56 class Game{ 57 ComputableStrategy strategy; 58 public Game(ComputableStrategy strategy){ 59 this.strategy = strategy; 60 } 61 public double getScore(double[] a){ 62 if(strategy != null) 63 return strategy.ComputeScore(a); 64 else 65 return 0; 66 } 67 }