策略模式:定义了算法族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化独立于使用算法的客户。
下面举个例子:
有两个具体策略,分别执行两个整型加法和减法。
interface Strategy { public abstract int handle(int a, int b);}public class AddOperation implements Strategy { public int handle(int a, int b) { return a+b; }}public class SubstractOperation implements Strategy { public int handle(int a, int b) { return a-b; }}public class Context { Strategy strategy; public Context(Strategy s) { strategy = s; } public void display(int a, int b) { int x = strategy.handle(a, b); System.out.println("result=" + x); }}public class Test { public static void main(String[] args) { Context c1 = new Context(new AddOperation()); c1.display(1,2); Context c2 = new Context(new SubstractOperation()); c2.display(1,2); }}
如此一来,就能在运行时改变选择的策略,具体策略与客户解耦了,就算具体策略的细节被改变,客户也不需要知道。