我根本不知道这个游戏,但只是按照你在这里说的:
多层次的层次结构可能会解决您的问题。就像如果 Artifacts 和 Lands 都有一些共同的行为,那么不要说 Artifact extends Permanent 和 Land extends Permanent,您可以创建另一个类,我们称之为 Property,然后说 Property extends Permanent,Artifact extends Property,Land extends Property。 (我想的是“不动产”和“个人财产”意义上的“财产”,而不是对象的财产。无论如何。)那么 Artifact 和 Land 共有的任何功能或数据都可以在 Property 中。
但如果存在不适用于 Creature 的 Artifact 和 Land 共有的行为,以及不适用于 Land 的 Artifact 和 Creature 共有的其他行为,则此方法不起作用。
Java 类不能扩展多个其他类,但它当然可以实现任意数量的类。因此,您可以为任何给定对象集的常见行为创建接口,例如可能由 Artifact 和 Creature 实现的 Movable 接口,以及将由 Artifact 和 Land 实现的 Property 接口等。但就像我一样你肯定意识到,这只继承了声明,而不是代码。因此,您最终将不得不多次实现相同的代码。
我偶尔做的一件事是创建另一个类来实现该行为,然后“真实”类将所有内容转发给实用程序类。因此,如果 - 并且我不了解游戏,所以我只是在编造示例 - Artifact 和 Land 都需要“购买”功能,您可以创建一个 Artifact 和 Land 都扩展的 Property 接口,创建一个包含实际代码的 PropertyImplementation 类,然后你会有类似的东西:
public class PropertyImplementation
{
public static void buy(Property property, Buyer buyer, int gold)
{
buyer.purse-=gold;
property.owner=buyer;
... etc, whatever ...
}
}
public interface Property
{
public static void buy(Property property, Buyer buyer, int gold);
}
public class Land extends Permanent implements Property
{
public void buy(Buyer buyer, int gold)
{
PropertyImplementation.buy(this, buyer, gold);
}
... other stuff ...
}
public class Artifact extends Permanent implements Property
{
public void buy(Buyer buyer, int gold)
{
PropertyImplementation.buy(this, buyer, gold);
}
... other stuff ...
}
不太复杂但有时非常实用的方法是在进行不适用的调用时抛出错误。喜欢:
public class Permanent
{
public void buy(Buyer buyer, int gold)
throws InapplicableException
{
buyer.purse-=gold;
this.owner=buyer;
... etc ...
}
}
public class Plainsman extends Permanent
{
// override
public void buy(Buyer buy, int gold)
throws InapplicableException
{
throw new InapplicableException("You can't buy a Plainsman! That would be slavery!");
}
}