简体   繁体   English

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

[英]Singleton instance of Palette Color cache

I have a list of CardView s that contain Bitmap s that return from the Network or from a LruCache . 我有一个列表CardView包含小号Bitmap s表示从网络或从返回LruCache

I also run a Palette.from(Bitmap).generate() operation on these bitmaps. 我还对这些位图运行了Palette.from(Bitmap).generate()操作。 This is expensive. 这很贵。 I would like to save these palette colors in a HashMap<...> of some sort. 我想将这些调色板颜色保存在某种HashMap<...>中。

This is the idea that I have, use HashMap<String, Integer> for each item name, and its corresponding color value. 这就是我的想法,为每个项目名称及其对应的颜色值使用HashMap<String, Integer>

If the name changes then change the color value. 如果名称更改,则更改颜色值。 The items in the list do not change that often so that is why I am considering using a HashMap<String, Integer> . 列表中的项目不会经常更改,因此这就是我考虑使用HashMap<String, Integer>

Secondly save this HashMap somewhere, maybe on the disk so when the user starts the app again there is no need to generate the Palette swatch if it already exists (and matches the name). 其次,将此HashMap保存在某个位置(可能在磁盘上),以便当用户再次启动该应用程序时,无需生成Palette色板(如果它已经存在(并且与名称匹配))。

I am thinking to implement it this way: 我正在考虑以这种方式实现它:

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

}

Any criticisms of this approach? 对这种方法有何批评? If so what are alternatives? 如果是这样,还有哪些替代方案?

That approach to lazy initialization of a singleton will fail in multithread applications. 这种单例的延迟初始化方法将在多线程应用程序中失败。

An alternative which does not have that problem and does not carry a performance hit is using an enum to implement the singleton. 一个没有问题并且不影响性能的替代方法是使用枚举实现单例。

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM