这是我为游戏继承的一些代码。该示例代码创建Armor。

目前,要制作一些新的Armor,您需要编写一个新的类。例如。

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

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




// ClothArmor.java
public class ClothArmor extends Armor {
    {
        name = "Cloth armor";
    }

    public ClothArmor() {
        super( 1 );
    }

    @Override
    public String desc() {
        return "Some Cloth Armor.";
    }
}


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

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

最佳答案

如果您的意图是向Armor动态添加某些行为,则可以使用Decorator设计模式。尝试看看here。它是GoF的书《设计模式》中使用最多的模式之一。

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

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;
    }
}

08-19 11:28