Java 使类更通用

Java 使类更通用,java,oop,design-patterns,Java,Oop,Design Patterns,这是我为一个游戏继承的一些代码。示例代码创建装甲 现在要制作一些新的盔甲,您需要编写一个新类。例如 // Armor.java public class Armor extends Item { public int tier; public Armor( int tier ) { this.tier = tier; } } 及 您将如何构造代码以使其更通用?从基于文本的配置文件中读取似乎很明显,但我可以看到,当您想创建一个具有特殊能力的装甲时,

这是我为一个游戏继承的一些代码。示例代码创建装甲

现在要制作一些新的盔甲,您需要编写一个新类。例如

// Armor.java
public class Armor extends Item {   
    public int tier;

    public Armor( int tier ) {
        this.tier = tier;
    }
}

您将如何构造代码以使其更通用?从基于文本的配置文件中读取似乎很明显,但我可以看到,当您想创建一个具有特殊能力的装甲时,这会遇到问题


是否有任何资源或设计模式可供我使用以确定如何进行?

如果您的目的是动态地向
装甲添加某些行为,则可以使用装饰设计模式。试着看一看。这是GoF的书《设计模式》中使用最多的模式之一

因此,如果我非常了解您的需求,您可以从文件中读取要添加到基本
装甲
的属性,然后使用工厂,使用装饰器模式将它们添加到装甲中


在类型层次结构中添加更多级别以添加功能总是很诱人的。但这并不总是最佳途径。有时,最好的方法是确定正交特征并提取它们。这里的关键是更喜欢组合而不是继承

所以在这种情况下,我会想一想
ClothArmour
Armour
有何不同,以及
Armour
物品有何不同?我要说的是,衣服盔甲与盔甲的不同之处在于它是由什么制成的,以及它所带来的奖励。然后我会说盔甲和道具的区别在于装备的位置

那么我会考虑去掉<代码> ClothArmour < /代码>和<代码>铠甲< /代码>。

Item clothArmour = new Item( 
                            EquipLocation.Chest, 
                            ComponentType.Cloth,
                            Bonuses.defenceOnEquip(1) );

为什么这是一种进步?它看起来不像是面向对象的。加载或保存这种格式相对来说很简单。

您在这里到底需要什么,您想做什么,以及如何使用这个类?这里您所说的“泛型”是什么意思?您的意思是从文本文件加载代码?简短回答:这在Java中是不可能的。当然这是可能的。两个版本:1。在运行时编译的文本文件中的Java代码(可能会变得复杂)。2.将JSON格式的项目写入文本文件,使用Jackson或Gson解析文件内容并将其映射到某个Java对象。非常简单。@BenjaminM您的第二个选项不会加载代码。它将加载数据。大多数def+从我这里得到1。
interface Armor {
    // Put public interface of Armor here
    public String desc();
}
class BaseArmor extends Item implements Armor {
    public int tier;
    public BaseArmor( int tier ) {
        this.tier = tier;
    }
    public String desc() {
        return "A base armor ";
    }
}
// Every new possible feature of an armor has to extend this class
abstract class ArmorDecorator implements Armor {
    protected final Armor armor;
    // The armor that we want to decorate
    public ArmorDecorator(Armor armor) {
        this.armor = armor;
    }
}
// An armor that is made of cloth
class MadeOfCloth extends ArmorDecorator {
    public MadeOfCloth(Armor armor) {
        super(armor);
    }
    @Override
    public String desc() {
        // Decoration: we add a feature to the desc method
        return armor.desc() + "made of Cloth ";
    }
}
// The factory that reads the properties file and build armors
// using the information read.
enum ArmorFactory {
    INSTANCE;
    public Armor build() {
        Armor armor = null;
        // At this point you have to had already read the properties file
        if (/* An armor made of cloth */) {
            armor = new MadeOfCloth(new BaseArmor(1));
        }
        return armor;
    }
}
Item clothArmour = new Item( 
                            EquipLocation.Chest, 
                            ComponentType.Cloth,
                            Bonuses.defenceOnEquip(1) );