简体   繁体   English

Java多个子类,但类型不同

[英]Java Multiple subclasses, but different types

Say I have a base class Base and it's subclasses SubA and SubB . 说我有一个基类Base ,它是SubASubB的子类。

public class Base(){

    public (static?) Animation anim;

    public Base(Frame[] frames){

        CpuIntensiveAnimationCreation(frames);

        // I need only one 'instance' of Animation Per subclass.
        // Every different TYPE of subclass needs it's own Animation instance.
        // A subclass can share one Animation, among multiple subclass-instances. (static?)

    }

See, I don't want to initialize a new Animation instance for every instance of a subclass I make, since it takes quite some time. 瞧,我不想为我创建的每个子类实例初始化一个新的Animation实例,因为这需要花费很多时间。 I do however need every subclass to have it's own Animation. 但是,我确实需要每个子类都具有自己的动画。
I could ofcourse have a static Animation per subclass and not use a superclass, but that would require a lot of redundant/copied code. 我当然可以每个子类都有一个静态Animation而不使用超类,但这将需要大量的冗余/复制代码。

How should I get to this? 我该怎么办?

Don't make it part of the class/subclass. 不要使其成为类/子类的一部分。 It would be a lot easier to have a 拥有一个会更容易

Map<Class<? extends Base>, Animation>

Create an animation registry as its own class and have it contain a mapping of classes to their animations. 创建一个动画注册表作为其自己的类,并使其包含类与其动画的映射。

My suggestion would be to have an abstract method getAnimation() in the base class. 我的建议是在基类中有一个抽象方法getAnimation()

Subclasses could then override this method to return a static Animation per subclass. 然后,子类可以重写此方法以为每个子类返回一个静态Animation。

So, you need a static field in your subclass to hold the animation you describe. 因此,您需要在子类中有一个静态字段来保存您描述的动画。

Now, you don't want to duplicate code, so you can put the method to generate that Animation in a static method on the Base class. 现在,您不想重复代码,因此可以将用于生成Animation的方法放在Base类的静态方法中。

Does that answer your question? 这是否回答你的问题?

How about in Base : Base如何:

You create a constructor that gets an instance of Subclass and instead of normal construction checks if it has an animation property and if not called the function initializing it statically for the class? 您创建了一个构造函数,该构造函数获取Subclass的实例,而不是通过常规构造检查其是否具有动画属性,以及是否未调用该函数为该类静态初始化的构造函数? It can inherit it from an abstract method in Base 它可以从Base的抽象方法继承它

That inverts the responsibility and causes the Base class to again be in charge the animation is there. 这就颠倒了责任,并使基类再次负责那里的动画。

1. Create a abstract method for getting Animation like getAnim() in Base class. 1.创建一个抽象方法来获取动画,例如在基类中使用getAnim()

2. Lets make Animation static in every Subclass , so all the instances of a Single subclass will share the same Animation instance . 2.每个子类中的Animation静态化 ,因此Single子类的所有实例将共享相同的Animation实例 So by doing this every class will have its own Animation. 因此,每个班级都有自己的动画。

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

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