背景
我正在用 Java 构建一个国际象棋程序。
问题
我创建了一个名为 IPiece
的接口(interface)类型:
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
接口(interface)中是否是一个糟糕的设计,因为它需要对任何派生类型进行强制转换。如果不进行强制转换,就无法计算结果。只是看起来很尴尬。当涉及类型转换时,我总是对设计进行二次猜测。
最佳答案
如果您确实想保留此接口(interface)结构,您可以向接口(interface)添加泛型类型。它定义了它可以敌对哪些棋子。这就是 Comparable
接口(interface)的作用,其工作原理如下:
public interface IPiece<E> {
boolean isFriendlyTo(E piece);
...
}
public abstract class AbstractChessPiece implements IPiece<AbstractChessPiece> {
...
@Override
public boolean isFriendlyTo(AbstractChessPiece piece) {
return this.color() == piece.color();
}
...
}
不过,我会选择 wakjah,并建议该接口(interface)声明一个 getColor
或 getPlayer
方法。
您应该只在两种不同的情况下使用相同的界面,如果它们以某种方式相互交互(例如跳棋棋子和国际象棋棋子可能会突然一起玩)。在你的例子中,游戏机制似乎是完全脱节的,因此使用不同的界面是有意义的。
如果您使用相同的代码来渲染两个游戏的图形,那么您可以定义另一个不包含游戏方法的接口(interface),例如 isFriendlyTo
。这会将共享图形功能与不相交的游戏功能分开。
关于java - 具有与声明类型相同的接口(interface)类型的参数的接口(interface)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19469850/