背景
我正在用Java构建一个国际象棋程序。
问题
我创建了一个名为的接口类型IPiece
:
public interface IPiece
{
boolean isFriendlyTo(IPiece piece);
Square[] destinationsFrom(IBasicBoard onBoard, Square fromSquare);
}
我正在执行它:
public abstract class AbstractChessPiece implements IPiece
{
private PieceArchetype pieceArchetype;
private Color color;
public AbstractChessPiece(PieceArchetype pieceArchetype, Color color)
{
this.pieceArchetype = pieceArchetype;
this.color = color;
}
public PieceArchetype archetype()
{
return this.pieceArchetype;
}
public Color color()
{
return this.color;
}
@Override
public boolean isFriendlyTo(IPiece piece)
{
if(this.equals(piece))
return true;
return this.isFriendlyTo((AbstractChessPiece) piece);
}
public boolean isFriendlyTo(AbstractChessPiece piece)
{
return this.color() == piece.color();
}
@Override
public abstract Square[] destinationsFrom(IBasicBoard onBoard, Square fromSquare);
}
我的问题与isFriendlyTo(IPiece)
方法有关。将这个方法包含在IPiece
接口中是不是一个糟糕的设计,因为它需要对任何派生类型进行强制转换。没有强制转换就无法计算结果。只是看起来很尴尬。当涉及到铸造时,我总是第二次猜测设计。