上周tute实现组合模式的时候,被tutor指出写了重复的代码,经过指导后,改进了自己编写代码的习惯,在此记录一下。
具体情景如下,在一个游戏中,不同轮次具有不一样的计分规则,最后取当前轮所有可用的规则所计算出的分值的最大值为最终分数,因此需要一个组合规则去管理规则,一开始我通过实例化三个rule对象去实现功能,被指出这样比较浪费空间而且冗余,因此通过一个ArrayList来实现,当到达对应轮次时再实例化当前轮可用规则的对象去计算分数,然后最后通过一个循环去找出最大值,避免了冗余比较和重复代码的问题。
public class CompositeRule implements iStrategy{
private ArrayList<Integer> r;
public CompositeRule(){
r = new ArrayList<Integer>();
}
@Override
public int calculator(int turn, BoardGame board, Player currentPlayer,ArrayList<Die> dices) {
// TODO Auto-generated method stub
r.add(new Rule1().calculator(turn, board, currentPlayer, dices));
if(turn%2 == 0) {
r.add(new Rule2().calculator(turn, board, currentPlayer, dices));
}
else if(turn%3 == 0) {
r.add(new Rule3().calculator(turn, board, currentPlayer, dices));
}
int tempScore = 0;
for(int i:r) {
if(i > tempScore) {
tempScore = i;
}
}
currentPlayer.addScore(tempScore);
return 0;
}
}