Cell 类应该包含所有后代的通用功能,并让他们实现差异。让我们找出什么是不同的,什么是共同的。
常见:
- 必须能够绘制所有单元格
- 所有细胞都必须能够被击中
- 所有细胞都有状态:是否被击中。
不同:
- 每个单元实现都有自己的绘制方法,具体取决于其状态。
- 每个单元实现都有自己的罢工反应:是未命中还是命中。
在实施过程中,您可以找到其他常见和不同功能的示例。
顺便说一句,如果我们分析它,结果表明细胞应该根据它的状态(被击中与否)来绘制自己。因为Miss 是一个受灾的Water 单元,所以你根本不需要单独的Miss 类。怀念刚刚遇水的状态。
因此,您的 Cell 类可能如下所示:
public abstract class Cell{
private boolean isStricken = false;
public void draw(){
if(isStricken){
drawStricken();
}else{
drawNotStricken();
}
}
public boolen strike(){
isStricken = true;
return isItHit();
}
protected abstract void drawNotStricken();
protected abstract void drawStricken();
protected abstract boolean isItHit();
}
而ShipSection 只会实现差异:
public class ShipSection extends Cell{
@Override
protected void drawNotStricken(){
//draw section
}
@Override
protected void drawStricken(){
//draw section in fire
}
@Override
protected boolean isItHit(){
return true
}
}
同样的方式你可以实现Water 类(正如你猜到的,水会在isItHit() 方法中返回false)。现在,例如,如果你有一个类BattleField,它包含所有单元格并将它们存储在数组中,接下来可以使用:
public class BattleField{
Cell[][] cellArray = new Cell[rowCount][colCount] ;
....
public void draw(){
for(Cell[]row : cellArray){
for(Cell cell : row){
cell.draw();
}
}
}
public boolean strike(int row, int col){
Cell cell = cellArray[row][col];
return cell.strike();
}
}
这段代码是简化的,只是为了演示一般的想法。如您所见,我们的BattleField 类对单元的实现一无所知,并将所有单元用作抽象Cell。
请记住,这只是类层次结构设计的示例,根据要求您可以自己制作,与此不同。希望这会有所帮助。