2012-02-21 155 views
0

我做在Java中的游戏,我只能和一个设计问题。 我的资源(图片,动画,声音)存储在几个HashMaps这样,每个类型的资源。这些(静态)hashmaps位于一个名为“Res”的静态类中。当一个实体需要一个资源时,它访问全局类的一个hashmaps,如果该资源不存在,它会自动加载。资源管理设计

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”的实例吗?还是有其他的选择?而且,这个资源管理系统是否良好实践? 在此先感谢!

+0

您可以使用(在引擎盖下静态实例)singleton设计模式。人们喜欢夸大这些单身人士是不好的。在大多数情况下 - 是的,但是在特定的情况下,在所需的情况下使用一个缓存实例。 – 2012-02-21 10:59:39

+0

单身人士比静态方法/会员有什么优势? – user10F64D4 2012-02-21 11:02:54

+0

单身保留传统类的做法,不要求您使用static关键字随处可见。起初他们可能要求更高,但会大大简化程序的架构。 – Rudy 2012-02-21 11:18:14

回答

0

使用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"); 
+0

在实现单例模式时使用枚举是一种很好的做法。 – assylias 2012-02-21 11:03:18

+0

阅读约翰Skeet的答案:http://stackoverflow.com/questions/427902/what-is-the-best-approach-for-using-an-enum-as-a-singleton-in-java – Rudy 2012-02-21 11:08:18

+0

谢谢!这有点长,但我会用它。 – user10F64D4 2012-02-21 11:37:58

0

保持简单。只要您不需要“资源缓存”的几个不同实例,就可以使用静态引用。

如果你担心其对各种对象的引用过多传递你的方法调用周围,你可以收集到所有对象的引用在“上下文”对象,只有通过围绕一个。