【发布时间】:2009-07-29 17:28:41
【问题描述】:
我目前正在开发一款 Java 集换式卡牌游戏,类似于旧版 Pokémon 游戏。我现在想做的是以某种方式定义所有卡片,但是因为有很多字段需要初始化,所以我正在考虑其他方法,因为构造函数会很长并且每张卡片都很难读取.我还必须初始化攻击,这意味着我必须基本上每次都创建一个匿名内部类(这个术语正确吗?),如下所示:
/**
* Base set Abra 43/102
*/
public final class Abra extends Pokemon
{
public Abra()
{
super(
new ImageIcon("img/scans/base-set/43-abra.jpg"),
"Abra",
"Base Set Abra",
null,
Type.PSYCHIC,
Type.PSYCHIC,
Type.NONE,
30,
0
);
attack1 = new Attack("Psyshock", Type.NORMAL)
{
/**
* 10 damage. Flip a coin. If heads, the Defending Pokémon is now Paralyzed.
*/
public void doAttack()
{
damageApplyWeaknessAndResistance(10);
if (gui.frames.CoinFlipDialog.showCoinFlipFrame() == CoinFlip.COIN_HEADS)
{
Game.getOpponentPlayer().getActivePokemon().status = Status.Paralyzed;
}
}
};
attack2 = null;
}
}
所以我的第二个选择是使用接口和抽象类创建层次结构,这意味着值不会存储在字段中,而是在需要时由方法返回:
public interface Card extends Cloneable, MouseListener, MouseMotionListener
{
public String getFullName();
public ImageIcon getSmallIcon();
public ImageIcon getFullIcon();
}
public interface Pokemon extends Card
{
public String getName();
public int getHPLeft();
public int getMaxHP();
public Type getType();
public Type getWeakness();
public Type getResistance();
public int getRetreatCost();
public Attack getAttack1();
public Attack getAttack2();
}
public class Abra extends AbstractPokemon
{
@Override
public Attack getAttack1()
{
return new Abra.PsyShock();
}
@Override
public Attack getAttack2()
{
return null;
}
@Override
public int getMaxHP()
{
return 30;
}
@Override
public String getName()
{
return "Base Set Abra";
} //etc...
所以我的问题是:这些方法是首选还是有更好的方法?
【问题讨论】:
标签: java constructor field