策略模式的定义是:定义一组算法,将每个算法都封装起来,并且在他们互相之间都可以切换。
下面是一个策略模式的通用源码,非常简单
1:抽象的策略较色
package strategy.common; public interface Strategy { //策略模式的运算法测 public void doSomething(); }
package strategy.common; public class ConcreteStrategy implements Strategy{ @Override public void doSomething() { // TODO Auto-generated method stub } }
package strategy.common; public class ConcreteStrategy1 implements Strategy{ @Override public void doSomething() { // TODO Auto-generated method stub } }
package strategy.common; public class Context { private Strategy strategy; public Context(Strategy strategy){ this.strategy=strategy; } public void doSomething(){ this.strategy.doSomething(); } }
package strategy.common; public class Client { //声明一个具体的策略 public static void main(String[] args) { Strategy strategy = new ConcreteStrategy(); Context context = new Context(strategy); context.doSomething(); } }
下面这个例子来自书本上的,这个枚举类型的策略角色我感觉用的很完美,在这里和大家分享一下,自己也把他记录下来,留着自己以后可以使用
package strategy; public enum Caculator { //加法运算 ADD("+"){ public int exec(int a, int b){ return a+b; } }, SUB("-"){ public int exec(int a,int b){ return a-b; } }; // String value = ""; //定义成员值类型 private Caculator(String _value){ this.value = _value; } //获得枚举成员的值 public String getValue(){ return this.value; } //声明一个抽象函数 public abstract int exec(int a,int b); }
package strategy; import java.util.Arrays; public class Client { public static void main(String[] args) { int a = Integer.parseInt("11"); String symo = "-"; int b = Integer.parseInt("12"); System.out.println("输入的参数为 " + Arrays.toString(args)); System.out.println("运行结果为 : "+ a+symo+b+"=" +Caculator.ADD.exec(a, b)); } }
原文:http://blog.csdn.net/u012516914/article/details/37612113