我倾向于删除Bowl
. 如果您发现自己处于这种情况,请问自己 - 我将如何处理 100 个实例Bowl
?Frame
考虑一下在游戏生命周期内必须创建和维护的十个实例。保留多个实例不是一个好主意,除非您需要多个实例来处理某些业务逻辑。
public class Bowl {
private int bowlScore;
// Use a no-argument constructor
public Bowl() {
this.bowlScore = 0;
}
public void setBowlScore( int score ) {
this.bowlScore = score;
}
public int getBowlScore() {
return this.bowlScore;
}
}
对于Frame
班级,
public class Frame {
private int frameScore;
private Bowl bowlArray[];
public Frame() {
this.frameScore = 0;
this.bowlArray = new Bowl[2];
}
public void setScoreForFirstBowl( int score ) {
this.bowlArray[0] = score;
this.frameScore += score;
}
public void setScoreForSecondBowl( int score ) {
this.bowlArray[1] = score;
this.frameScore += score;
}
public void setFrameScore( int score ) {
this.frameScore = score;
}
public int getFrameScore() {
return this.frameScore;
}
// this should not be used, left in for completeness
public Bowl[] getBowlArray() {
return this.bowlArray;
}
}
而对于Game
public class Game {
private int gameScore;
private ArrayList<Frame> gameFrames;
public Game() {
this.gameScore = 0;
this.gameFrames = new ArrayList<Frame>();
}
/* There are many ways of implementing the game logic. Here is an example.
You will have to complete the rest :) */
// @frame frame object with bowl data that is appended to list
public void frameCompleted(Frame frame) {
this.gameScore += frame.getFrameScore; // I assume this is what you want to do. Change if not
this.gameFrames.add(frame);
}
/* The method written above can also be implemented by passing integer values
for the score, bowl number and frame number. However, this would not be very
OOP friendly. Essentially, this is 'Encapsulation' of the Frame data into the
Frame object. */
// Add getters and setters for gameScore and gameFrames
}
有关进一步使用的示例,请参阅ArrayList文档。如果您不想使用它,可以将其替换为数组。我包括它只是为了展示列表能力。
在此处和此处阅读有关封装 的更多信息。
Bowl
你会注意到我在orFrame
类中没有考虑到“罢工” 。这是因为它是一个需要满足的特殊情况,所以我把它留给你来实现。我的理解是,如果你在第一个碗上投出好球,你就不会得到第二个碗。