zoukankan      html  css  js  c++  java
  • Java设计模式之策略模式(13)

    策略模式定义了一系列算法,每个算法封装起来,他们可以相互替换,且算法的变化不会影响到使用算法的客户。可以设计一个抽象类提供辅助。

    package WHP;
    
    public interface ICalculator {
        public int calculate(String exp);
    }
     1 package WHP;
     2 
     3 public class AbstractCalculator {
     4 
     5     public int[] split(String exp, String opt) {
     6         // TODO Auto-generated method stub
     7         String array[] = exp.split(opt);
     8         int arrayInt[] = new int[2];
     9         arrayInt[0] = Integer.parseInt(array[0]);
    10         arrayInt[1] = Integer.parseInt(array[1]);
    11         return arrayInt;
    12     }
    13 }
    AbstractCalculator
     1 package WHP;
     2 
     3 public class Plus extends AbstractCalculator implements ICalculator {
     4 
     5     public int calculate(String exp) {
     6         // TODO Auto-generated method stub
     7         int arrayInt[]=split(exp,"\+");        
     8         return arrayInt[0]+arrayInt[1];
     9     }
    10 }
    Plus
     1 package WHP;
     2 
     3 public class Minus extends AbstractCalculator implements ICalculator {
     4 
     5     public int calculate(String exp) {
     6         // TODO Auto-generated method stub
     7         int arrayInt[] = split(exp, "-");
     8         return arrayInt[0] + arrayInt[1];
     9     }
    10 }
    Minus
  • 相关阅读:
    Codeforces_739_B
    Codeforces_732_D
    D
    C
    E
    商汤AI园区的n个路口(中等)
    D. The Fair Nut and the Best Path
    HDU6446
    分解质因数(线性筛)
    D. Extra Element
  • 原文地址:https://www.cnblogs.com/netact/p/3843511.html
Copyright © 2011-2022 走看看