描述
策略模式定义了一系列算法,并将每个算法封装起来,使他们可以相互替换,且算法的变化不会影响到使用算法的客户。需要设计一个接口,为一系列实现类提供统一的方法,多个实现类实现该接口,设计一个抽象类(可有可无,属于辅助类),提供辅助函数
示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| interface ICalculator{ public int calculate(String exp); }
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; } }
class Plus extends AbstractCalculator implements ICalculator{ @Override public int calculate(String exp){ int arrayInt[] = split(exp, "\\+"); return arrayInt[0]+arrayInt[1]; } } class Minus extends AbstractCalculator implements ICalculator{ @Override public int calculate(String exp){ int arrayInt[] = split(exp, "\\-"); return arrayInt[0]-arrayInt[1]; } } class Multiply extends AbstractCalculator implements ICalculator{ @Override public int calculate(String exp){ int arrayInt[] = split(exp, "\\*"); return arrayInt[0]*arrayInt[1]; } }
public class Test { public static void printMsg(String msg){ System.out.println(msg); } public static void main(String[] args){ String exp= "2+8"; ICalculator cal = new Plus(); int result = cal.calculate(exp); Test.printMsg(Integer.toString(result)); } }
|