gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 13:31:30 26 4
gpt4 key购买 nike

我有一个列表 CardView包含 Bitmap 的从网络或 LruCache 返回的.

我还运行了 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);
}

}

关于java - 调色板颜色缓存的单例实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32163729/

26 4 0
文章推荐: html - 带有边框 css 的大纲 div?
文章推荐: javascript - 播放后重定向 html5 视频
文章推荐: javascript - 动态获取 元素的第 n 个
innerHTML