簡體   English   中英

資源管理設計

[英]Resource management design

我正在用Java開發游戲,並且遇到了設計問題。 我的資源(圖像,動畫,聲音)存儲在幾個HashMap中,每種類型的資源都有一個。 這些(靜態)哈希圖位於稱為“ Res”的靜態類中。 當實體需要資源時,它會訪問全局類的哈希表之一,如果該資源不存在,則會自動加載它。

    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”的實例嗎? 還是還有其他選擇? 而且,此資源管理系統是否是好的做法? 提前致謝!

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

把事情簡單化。 只要您不需要“資源緩存”的多個不同實例,就可以使用靜態引用。

如果您擔心在方法調用中必須傳遞太多對各種對象的引用,則可以在“上下文”對象中收集對所有對象的引用,而只能傳遞該對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM