我在用java做游戏,但遇到了一个设计问题。我的资源(图像、动画、声音)存储在几个HashMaps中,每种资源对应一个。这些(静态)hashmap位于一个名为"Res“的静态类中。当一个实体需要一个资源时,它会访问全局类的一个hashmap,如果这个资源不存在,它会被自动加载。
static Map<String, Sprite> sprites = new HashMap<>();
static Map<String, BufferedImage> images = new HashMap<>();
static Map<String, Clip> sounds = new HashMap<>();
static Map<String, Font> fonts = new HashMap<>();我的问题是:这个设计足够好吗?我读到过静态函数是不好的实践,但是我必须每次都传递"Res“类的实例吗?或者还有其他选择吗?还有,这个资源管理系统是不是很好的实践?提前感谢!
发布于 2012-02-21 18:41:55
使用Singleton来维护所有资源,而不是这些静态函数。
public class ResourceSingleton {
private Map<String, Sprite> sprites = new HashMap<>();
private Map<String, BufferedImage> images = new HashMap<>();
private <String, Clip> sounds = new HashMap<>();
private <String, Font> fonts = new HashMap<>();
public Map getSprites()
{return sprites;}
public void setSprites(Map<String,Sprite> sprites)
{ this.sprites = sprites; }
//generate other getter setter
// Private constructor prevents instantiation from other classes
private ResourceSingleton() { }
private static class SingletonHolder {
public static final Singleton instance = new Singleton();
//populate your resource here.
}
public static ResourceSingleton getInstance() {
return SingletonHolder.instance;
}}
要使用该资源,只需调用
ResourceSingleton res = ResourceSingleton.getInstance();
Sprite firstSprite = res.getSprites().get("firstSprite");发布于 2012-02-21 18:44:11
保持简单。只要你不需要你的“资源缓存”的几个不同的实例,使用静态引用是可以的。
如果你担心在你的方法调用中必须传递太多对各种对象的引用,你可以在一个“上下文”对象中收集对所有对象的引用,然后只传递那个对象。
https://stackoverflow.com/questions/9375980
复制相似问题