java设计模式 — 策略模式

作者: 出来混要还的 | 来源:发表于2019-09-16 10:00 被阅读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));
      }
    
    }
    

    相关文章

      网友评论

        本文标题:java设计模式 — 策略模式

        本文链接:https://www.haomeiwen.com/subject/yisdyctx.html