2012-02-21 97 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

保持簡單。只要您不需要「資源緩存」的幾個不同實例,就可以使用靜態引用。

如果你擔心其對各種對象的引用過多傳遞你的方法調用周圍,你可以收集到所有對象的引用在「上下文」對象,只有通過圍繞一個。