调色板颜色缓存的单例实例

Singleton instance of Palette Color cache

我有一个 CardView 列表,其中包含 Bitmap 来自网络或 LruCache 的 return。

我还运行对这些位图进行了Palette.from(Bitmap).generate()操作。这很贵。我想将这些调色板颜色保存在某种 HashMap<...> 中。

这是我的想法,每个项目名称使用HashMap<String, Integer>,以及它对应的颜色值。

如果名称更改,则更改颜色值。列表中的项目不会经常更改,所以这就是我考虑使用 HashMap<String, Integer>.

的原因

其次将此 HashMap 保存在某处,也许在磁盘上,这样当用户再次启动应用程序时,如果 Palette 样本已经存在(并且与名称匹配),则无需生成样本.

我想这样实现:

public class PaletteCache {

    private static PaletteCache sPaletteCache;
    private static HashMap<String, Integer> mCache;

    private PaletteCache() { 
        loadCache();
    }

    public static PaletteCache getInstance() {
        if (sPaletteCache == null)
            sPaletteCache = new PaletteCache();
        return sPaletteCache;
    }

    private static void loadCache() {
        // Load the HashMap from disk if present
    }

    public static int getVibrantColor(String itemName) {
        return mCache.get(itemName);
    }

    public static void setColor(String itemName, int color) {
        mCache.put(itemName, color);
    }

}

对这种方法有什么批评吗?如果可以,还有哪些替代方案?

单例延迟初始化的方法在多线程应用程序中会失败。

没有该问题且不影响性能的替代方法是使用枚举来实现单例。

public enum PaletteCache
{
    INSTANCE;

    private static HashMap<String, Integer> mCache;

    private PaletteCache() {
        loadCache();
    }

    public static PaletteCache getInstance() {
        return INSTANCE;
    }

    private static void loadCache() {
        // Load the HashMap from disk if present
    }

    public static int getVibrantColor(String itemName) {
        return mCache.get(itemName);
    }

    public static void setColor(String itemName, int color) {
        mCache.put(itemName, color);
    }

}