[英]Which is better Java programming practice: stacking enums and enum constructors, or subclassing?
給定有限種類的項目,是否最好用堆疊的枚舉和枚舉構造器來表示它們,或者將它們子類化? 還是完全有更好的方法?
為了給您一些背景信息,在我的小型RPG程序中(諷刺的是,它很簡單),角色的庫存中有不同種類的物品。 物品因其類型,用途和效果而異。
例如,清單中的一項是名為Gremlin的咒語滾動,可調整Utility屬性。 另一個物品可能是稱為Mort的劍,用於戰斗並造成傷害。
在我的RPG代碼中,我現在嘗試了兩種表示庫存物料的方法。 一種方法是子類化(例如,InventoryItem-> Spell-> AdjustingAttributes; InventoryItem-> Weapon-> Sword),並在需要時實例化每個子類,並分配諸如Gremlin和Mort之類的值。
另一種方法是通過堆疊枚舉和枚舉構造函數。 例如,我為itemCategory和itemSpellTypes和itemWeaponTypes創建了枚舉,而InventoryItem枚舉是這樣的:
public enum InventoryItem {
GREMLIN(itemType.SPELL, itemSpellTypes.ATTRIBUTE, Attribute.UTILITY),
MORT(itemType.WEAPON, itemWeaponTypes.SWORD, 30);
InventoryItem(itemType typeOfItem, itemSpellTypes spellType, Attribute attAdjusted) {
// snip, enum logic here
}
InventoryItem(itemType typeOfItem, itemWeaponTypes weaponType, int dmg) {
// snip, enum logic here
}
// and so on, for all the permutations of items.
}
是否有比這兩種方法更好的Java編程實踐? 或者,如果只有這些方法,那么哪種更好? 預先感謝您的建議。
如果枚舉僅包含靜態數據且邏輯最少(最好根本沒有邏輯),則枚舉會很好。 如果您的對象根據其種類而具有不同的行為,通常最好將它們實現為子類。
正如其他人提到的那樣,您很有可能向對象添加屬性,而這些屬性對所有類型都沒有意義。 例如。 顏色屬性對武器有意義但對咒語沒有意義。 在這種情況下,武器和咒語不應位於同一枚舉中。
如果要向項目添加新屬性,將它們實現為子類可能會更容易。 這樣,如果一組項目獲得新屬性,它將傳播到所有子類。
例如,如果各種Weapon
都分配了一定的權重,則只需將該屬性添加到該類中即可。 然后,此屬性將傳播到子類。
對於本質上是靜態的,因此可以直接分配類型的其他事物,枚舉是好的。 我在這里自由思考,所以我想Weapon
可能會分配一個DamageType
:
public abstract class Weapon {
public enum DamageType {
CUT,
SMASH,
PIERCE;
}
private DamageType damageType;
在上下文中,我將考慮使用類層次結構而不是枚舉定義,並使用接口來補充該層次結構。 例如
/**
* Root of class hierarchy.
*/
public interface InventoryItem {
}
/**
* Additional "parallel" interface implemented by some (but not all)
* InventoryItems and other non-inventory items.
*/
public interface Usable {
void use();
}
/**
* A Spell is in InventoryItem and is also Usable.
*/
public abstract class Spell implements InventoryItem, Usable {
}
public class Gremlin extends Spell {
}
/**
* A Door is *not* an InventoryItem but can be used.
*/
public class Door implements Usable {
}
這種方法的主要優點是,它允許您在不同的上下文中對待給定的對象(作為InventoryItem
或Usable
的列表)。 我要避免使用枚舉的另一個原因是,您可能會定義項目的行為(例如spell.cast(Person)
),而這在枚舉IMHO中並不理想。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.