Java设计模式java全栈之设计模式java中的设计模式

java设计模式 — 策略模式

2019-09-16  本文已影响0人  出来混要还的

1. 定义策略接口

/**
 * @author zhangzhen
 */
public interface ComputableStrategy {

  double computableScore(double[] a);
}

2. 实现策略

  1. 平均分
    /**
     * @author zhangzhen
     */
    public class StrategyOne implements ComputableStrategy {
    
      @Override
      public double computableScore(double[] a) {
        double avg = 0, sum = 0;
        for (double d : a) {
          sum += d;
        }
        avg = sum / a.length;
        return avg;
      }
    
    }
    

2.几何分

/**
 * @author zhangzhen
 */
public class StrategyTwo implements ComputableStrategy {


  @Override
  public double computableScore(double[] a) {
    double score = 0, multi = 1;
    int n = a.length;
    for (double d : a) {
      multi = multi * d;
    }
    score = Math.pow(multi, 1.0 / n);
    return score;
  }

}
  1. 去最大、最小后平均分
    /**
     * @author zhangzhen
     */
    public class StrategyThree implements ComputableStrategy {
    
      @Override
      public double computableScore(double[] a) {
        double score = 0, sum = 0;
        if (a.length <= 2)
          return 0;
        Arrays.sort(a);
        for (int i = 1; i < a.length - 1; i++) {
          sum += a[i];
        }
        score = sum / (a.length - 2);
        return score;
      }
    
    }
    

3. 策略调用封装

/**
 * @author zhangzhen
 */
public class GymnasticsGame {

  ComputableStrategy strategy;

  public void setStrategy(ComputableStrategy strategy) {
    this.strategy = strategy;
  }

  public double getPersonScore(double a[]) {
    if (strategy != null) {
      return strategy.computableScore(a);
    } else {
      return 0;
    }
  }
}

4. 测试

/**
 * @author zhangzhen
 */
public class Application {

  /**
   * @param args
   */
  public static void main(String[] args) {

    GymnasticsGame game = new GymnasticsGame();

    game.setStrategy(new StrategyOne());
    double[] a = { 8.5, 8.8, 9.5, 9.7, 10 };
    // 平均分
    System.out.println(game.getPersonScore(a));
    
    game.setStrategy(new StrategyTwo());
    // 几何分
    System.out.println(game.getPersonScore(a));

    game.setStrategy(new StrategyThree());
    // 去掉最大、最小后的平均分
    System.out.println(game.getPersonScore(a));
  }

}
上一篇 下一篇

猜你喜欢

热点阅读