1. 定义策略接口
/**
* @author zhangzhen
*/
public interface ComputableStrategy {
double computableScore(double[] a);
}
2. 实现策略
- 平均分
/** * @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;
}
}
- 去最大、最小后平均分
/** * @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));
}
}