Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/design-patterns/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 资源管理设计_Java_Design Patterns_Resources - Fatal编程技术网

Java 资源管理设计

Java 资源管理设计,java,design-patterns,resources,Java,Design Patterns,Resources,我正在用java制作一个游戏,我遇到了一个设计问题。 我的资源(图像、动画、声音)存储在几个哈希图中,每种类型的资源对应一个哈希图。这些(静态)哈希映射位于一个名为“Res”的静态类中。当一个实体需要一个资源时,它访问全局类的一个hashmaps,如果该资源不存在,它将自动加载 static Map<String, Sprite> sprites = new HashMap<>(); static Map<String, BufferedImage>

我正在用java制作一个游戏,我遇到了一个设计问题。 我的资源(图像、动画、声音)存储在几个哈希图中,每种类型的资源对应一个哈希图。这些(静态)哈希映射位于一个名为“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<>();
staticmap sprites=newhashmap();
静态映射图像=新的HashMap();
静态映射声音=新HashMap();
静态映射字体=新建HashMap();
我的问题是:这个设计足够好吗?我已经读过静态函数是不好的实践,但是每次我都必须传递类“Res”的实例吗?或者还有其他选择吗?而且,这种资源管理系统是良好的实践吗? 提前谢谢

用于维护所有资源,而不是这些静态函数

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;
    }

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


如果您担心必须在方法调用中传递太多对各种对象的引用,您可以在“上下文”对象中收集对所有对象的引用,并只传递该引用。

您可以使用单例设计模式(引擎盖下的静态实例)。人们喜欢夸大其词地说单身汉不好。在大多数情况下-是的,但在您的特定情况下,在所需的情况下使用一个缓存实例。与静态方法/成员相比,singleton有什么优势?singleton保留了传统的类方法,并且不要求您在任何地方都使用static关键字。一开始它们的实现要求可能更高,但会大大简化程序的体系结构。在实现单例模式时使用枚举是一种很好的做法。请阅读John Skeet的回答:谢谢!稍长一点,但我会用的。
ResourceSingleton res = ResourceSingleton.getInstance();
Sprite firstSprite = res.getSprites().get("firstSprite");