java设计模式 — 策略模式

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));
  }

}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 在我们需要实现一个功能的时候,可以有多种算法来实现的时候,我们可以使用if...else或者case来选择对应的算...
    MrKing5946阅读 231评论 0 0
  • Java经典问题算法大全 /*【程序1】 题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子...
    赵宇_阿特奇阅读 1,895评论 0 2
  • 在C语言中,五种基本数据类型存储空间长度的排列顺序是: A)char B)char=int<=float C)ch...
    夏天再来阅读 3,392评论 0 2
  • 策略模式,顾名思义,我是没看懂。 不知道为什么称它为策略模式,但通过学习,我知道这种模式可以让我的代码分工明确,实...
    废柴傻狗阅读 690评论 1 6
  • 定义 Define a family of algorithms,encapsulate each one,and...
    tianranll阅读 355评论 0 2