我是否可以为每种不同类型的继承类使用静态变量的不同副本 [英] Can I have different copies of a static variable for each different type of inheriting class

查看:99
本文介绍了我是否可以为每种不同类型的继承类使用静态变量的不同副本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望根据类的类型使用不同的静态变量。

I want to have the same static variable with a different value depending on the type of class.

所以我会

public class Entity
{
     public static Bitmap sprite;

     public void draw(Canvas canvas, int x, int y)
     {
          canvas.drawBitmap(sprite, x, y, null);
     }
}

public class Marine extends Entity
{

}

public class Genestealer extends Entity
{

}

然后在我的主程序中去:

And then in my main program go:

Marine.sprite = // Load sprite for all instances of Marine
Genestealer.sprite = // Load sprite for all instances of Genestealer

我不想在类的每个实例中存储相同的sprite 。我希望每种类型都有一个。我想继承静态精灵变量和绘制精灵的绘制函数。但我不希望Genstealer精灵覆盖海洋精灵。

I don't want to store the same sprite in every instance of the class. I want one for each type of class. I want to inherit the static sprite variable and the draw function which will draw the sprite. But I don't want the Genstealer sprite to override the Marine sprite.

这可能吗?

如何我会这样做吗?

推荐答案

使用抽象方法:

public class Entity
{
     public abstract Bitmap getSprite();

     public void draw(Canvas canvas, int x, int y)
     {
          canvas.drawBitmap(getSprite(), x, y, null);
     }
}

public class Marine extends Entity
{
    public Bitmap getSprite() {
        return /*the sprite*/;
    }
}

如果你的话,getSprite返回的精灵可以是静态的喜欢。关于这种方法的好处:

The sprite returned by getSprite can be a static if you like. Nice things about this approach:


  • 你不能(很容易)忘记在你的子类中包含一个sprite,因为编译器如果你没有实施抽象方法,我们会抱怨。

  • You can't (easily) forget to include a sprite in your subclass, since the compiler will complain if you don't implement the abstract method.

它很灵活。假设海军陆战队员一旦升级就应该看起来不同。只需更改Marine的getSprite方法即可将该级别考虑在内。

It's flexible. Suppose a Marine should look different once he "levels up". Just change Marine's getSprite method to take the level into account.

这是标准的OO-idiom,因此人们会看到他们的代码赢了不要挠头。

It's the standard OO-idiom for this sort of thing, so people looking at their code won't be left scratching their heads.

这篇关于我是否可以为每种不同类型的继承类使用静态变量的不同副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆