标签:
什么时候使用:
有很多算法,都是为了做一件事,使用相同的数据源,通过这些不同的算法,得到相同或者不同的结果。
例如对一组数据进行排序,提供了快排、冒泡、直接排序等算法,然后根据需要动态的选择其中的一种。
关键:
将算法封装成一个一个的类,任意地替换。有一个Context类,可以动态的配置使用的策略(Strategy)。
代码:
创建策略接口:Strategy.java
public interface Strategy { public int doOperation(int num1, int num2); }
创建实现接口的实体类:
OperationAdd.java
public class OperationAdd implements Strategy{ @Override public int doOperation(int num1, int num2) { return num1 + num2; } }
OperationSubstract.java
public class OperationSubstract implements Strategy{ @Override public int doOperation(int num1, int num2) { return num1 - num2; } }
OperationMultiply.java
public class OperationMultiply implements Strategy{ @Override public int doOperation(int num1, int num2) { return num1 * num2; } }
创建Context类:Context.java
public class Context { private Strategy strategy; public Context(Strategy strategy){ this.strategy = strategy; } public int executeStrategy(int num1, int num2){ return strategy.doOperation(num1, num2); } }
Context类体现了,策略作为一个对象动态的传入,而导致不同的行为。
运行demo:
StrategyPatternDemo.java
public class StrategyPatternDemo { public static void main(String[] args) { Context context = new Context(new OperationAdd()); System.out.println("10 + 5 = " + context.executeStrategy(10, 5)); context = new Context(new OperationSubstract()); System.out.println("10 - 5 = " + context.executeStrategy(10, 5)); context = new Context(new OperationMultiply()); System.out.println("10 * 5 = " + context.executeStrategy(10, 5)); } }
输出:
10 + 5 = 15 10 - 5 = 5 10 * 5 = 50
标签:
原文地址:http://www.cnblogs.com/zhang-chi/p/5938125.html