繁体   English   中英

参数类型与声明类型相同的接口方法

[英]Interface method with parameter of same interface type as declaring type

背景

我正在用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)的问题是isFriendlyTo(IPiece)方法。 IPiece接口中包含此方法是否不好,因为它需要对任何派生类型进行IPiece 没有强制转换就无法计算结果。 看起来很尴尬。 当涉及铸造时,我总是会第二次猜测一个设计。

如果确实要保留此接口结构,则可以向该接口添加泛型。 它定义了它可以敌对的部分。 这是Comparable接口的作用,其工作方式如下:

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,建议接口声明一个getColor或一个getPlayer方法。

如果它们以某种方式相互交互(例如,棋子和国际象棋可能会突然一起玩),则只能在两种不同情况下使用同一界面。 在您的情况下,游戏机制似乎是完全不相交的,因此为此使用不同的界面是有意义的。

如果您使用相同的代码来渲染两个游戏的图形,则可以定义另一个接口,该接口不包括isFriendlyTo类的游戏方法。 这将共享的图形功能与不玩的游戏功能分开。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM