Java设计模式之策略模式

来源:互联网 发布:马小丝的淘宝店 编辑:程序博客网 时间:2024/06/05 09:46

策略模式(strategy)

概念:
定义一组算法,并把其封装到一个对象中。然后在运行时,可以灵活的使用其中的一个算法。

适用:
1.多个类只区别在表现行为不同,可以使用Strategy模式,在运行时动态选择具体要执行的行为。
2.需要在不同情况下使用不同的策略(算法),或者策略还可能在未来用其它方式来实现。
3.对客户隐藏具体策略(算法)的实现细节,彼此完全独立。

代码示例:

/** * 所有策略的抽象接口 * 提供计算方法的接口 */public interface ICalculator {      public int calculate(String exp);  }
/** * 辅助类 */public abstract class AbstractCalculator {      public int[] split(String exp,String opt){          String array[] = exp.split(opt);          int arrayInt[] = new int[2];          arrayInt[0] = Integer.parseInt(array[0]);          arrayInt[1] = Integer.parseInt(array[1]);          return arrayInt;      }  } 
/** * 具体的策略实现  * 相减计算 */public class Minus extends AbstractCalculator implements ICalculator {      public int calculate(String exp) {          int arrayInt[] = split(exp,"-");          return arrayInt[0]-arrayInt[1];      }  }  
/** * 具体的策略实现  * 相乘计算 */public class Multiply extends AbstractCalculator implements ICalculator {      public int calculate(String exp) {          int arrayInt[] = split(exp,"\\*");          return arrayInt[0]*arrayInt[1];      }  }
/** * 具体的策略实现  * 相加计算 */public class Plus extends AbstractCalculator implements ICalculator {      public int calculate(String exp) {          int arrayInt[] = split(exp,"\\+");          return arrayInt[0]+arrayInt[1];      }  } 
/** * 策略模式的测试 * 根据不同的策略执行不同的动作 */public class Test {      public static void main(String[] args) {          String exp = "2+8";          ICalculator cal = new Plus();  // 相加策略        int result = cal.calculate(exp);          System.out.println(result);    }  }
原创粉丝点击