简体   繁体   English

如何设计一个类层次结构,该类层次结构提供有关子类的信息而无需实例化它

[英]How to design a class hierarchy which gives information about the subclasses without instantiating it

I'm trying to design classes for spells in a game. 我正在尝试为游戏中的咒语设计类。

First i have a player with a spelbook, which indicates which spells are available for this player 首先,我有一位玩家,并且带有一本练习簿,其中指出了该玩家可以使用哪些咒语

public class Player {
    private List<Class<? extends Spell>> speellBook;
}

now i created some spells 现在我创造了一些咒语

public abstact class Spell { 
    public abstact double getDmg(); 
    private double position x;
    private double position y;
}
public class FireBolt extends Spell {
    public double getDmg() { return 15; }
}
public class FrostBolt extends Spell {
    public double getDmg() { return 10; }
}

Now i want to show a tooltip about the FireBolt, which shows that this spell does 15 damage whithout instantiating it. 现在,我想显示一个有关FireBolt的工具提示,该提示表明即使不实例化此法术也会造成15点伤害。 It should only instantiated when the player really casts it. 它应该仅在玩家真正投放时实例化。

I already thought of a static field but static fields cannot be overidden by the real spells. 我已经想到了静态字段,但是静态字段不能被真正的咒语所取代。

Then i thought of an singleton pattern, but since i store the current position in my spells, too, this won't work either 然后我想到了单例模式,但是由于我也将当前位置存储在我的咒语中,所以这也不起作用

Is there any standard pattern for this? 是否有任何标准模式? I only found the prototype-pattern but sice i need a singleton it won't be inheritable 我只找到了原型模式,但是我需要一个单例,它将无法继承

You're trying to apply the inheritance (uniformly call getDmg method on different spells) for classes, avoiding objects instantiation. 您正在尝试为类应用继承(在不同的咒语上统一调用getDmg方法),以避免对象实例化。 As you already noticed, these requires static fields and a static method, but they do not work with inheritance. 正如您已经注意到的那样,它们需要静态字段和静态方法,但是它们不适用于继承。 I've seen these many times and it does not work in that way. 我已经看过很多次了,但这种方式不起作用。

I suggest creating template objects and use them for displaying tooltip. 我建议创建模板对象并将其用于显示工具提示。 Example: 例:

public class SpellTooltip {

    private Map<Class<? extends Spell>, Spell> templates = new HashMap<>();

    {
        templates.put(Firebolt.class, new Firebolt());
        templates.put(Frostbolt.class, new Frostbolt());
    }

    public int getSpellDamage(Class<? extends Spell> clazz) {
        return templates.get(clazz).getDmg();
    }
}

The implementation can vary based on the complexity of your design. 实现可能会根据设计的复杂性而有所不同。 Using it as-is, you should always remember about adding new types to the map. 照原样使用它,您应该始终记住要向地图添加新类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM