本文共 3617 字,大约阅读时间需要 12 分钟。
定义一系列算法,把它们一个个封装起来,并且使它们可相互替换。本模式使得算法可独立于使用它的客户而变化。
Define a family of algorithms, encapsulate each one, and make them inter changeable. Strategy lets the algorithm vary independently from clients that use it.
策略方法模式的结构中包括三种角色。
+ 策略(Strategy):策略是一个接口,该接口定义若干个算法标识,即定义了若干个抽象方法。 + 具体策略(Concrete Strategy):具体策略是实现策略接口的类。具体策略实现策略接口所定义的抽象方法,即给出算法标识的具体算法。 + 上下文(Context):上下文是依赖于策略接口的类,即上下文包含有策略声明的变量。上下文中提供一个方法,该方法委托策略变量调用具体策略所实现的策略接口中的方法。package Strategy;public interface ComputableStrategy { public abstract double computableStrategy(double[] a);}
package Strategy;public class StrategyOne implements ComputableStrategy { @Override public double computableStrategy(double[] a) { double score = 0, sum = 0; for (int i = 0; i < a.length; i++) { sum = sum + a[i]; } score = sum/a.length; return score; }}
package Strategy;public class StrategyTwo implements ComputableStrategy { @Override public double computableStrategy(double[] a) { double score = 0, multi = 1; int n = a.length; for (int i = 0; i < a.length; i++) { multi = multi * a[i]; } score = Math.pow(multi, 1.0/n); return score; }}
package Strategy;import java.util.Arrays;public class StrategyThree implements ComputableStrategy { @Override public double computableStrategy(double[] a) { if (a.length <= 2) return 0; double score = 0, sum = 0; Arrays.sort(a); for (int i = 1; i < a.length - 1; i++) { sum = sum + a[i]; } score = sum/(a.length-2); return score; }}
package Strategy;public class GymnasticsGame { ComputableStrategy strategy; public void setStrategy(ComputableStrategy strategy) { this.strategy = strategy; } public double getPersonScore(double a[]) { if (strategy != null) { return strategy.computableStrategy(a); } else return 0; }}
package Strategy;public class Application { public static void main(String[] args) { GymnasticsGame game = new GymnasticsGame(); game.setStrategy(new StrategyOne()); Person zhang = new Person(); zhang.setName("张三"); double[] a = { 9.12, 9.25, 8.87, 9.99, 6.99, 7.88}; Person li = new Person(); li.setName("李四"); zhang.setScore(game.getPersonScore(a)); li.setScore(game.getPersonScore(a)); System.out.println(zhang.getScore()); System.out.println(li.getScore()); game.setStrategy(new StrategyThree()); zhang.setScore(game.getPersonScore(a)); li.setScore(game.getPersonScore(a)); System.out.println(zhang.getScore()); System.out.println(li.getScore()); }}class Person { String name; double score; public String getName() { return name; } public void setName(String name) { this.name = name; } public double getScore() { return score; } public void setScore(double score) { this.score = score; }}
转载地址:http://liroa.baihongyu.com/