我有一个应用程序,我需要两个静态缓存,一次是短期缓存,一次是长期缓存。
所以我有一个看起来像这样的抽象类。我的想法是我会创建两个继承自这个抽象类的类,从而获得我的两个静态类。
然而,我发现我正在创建3个对象,而我可以使用其中一个。但我不知道该怎么做。我想要某种工厂类吗?
有人可以在这里建议一个合适的模式吗?
public abstract class myCache {
static Map<String, Object> ObjectCache = new ConcurrentHashMap<String, Object>();
public void put(String Key, T cmsObject) {
//
}
public xxx static get(String objectKey, Class<T> type) {
//
}
}
答案 0 :(得分:1)
public abstract class myCache {
static ConcurrentMap<Class<?>,Map<String, Object>> ObjectCache = new ConcurrentHashMap<Class<?>,Map<String, Object>>();
{
ObjectCache.putIfAbsent(getClass(),new ConcurrentHashMap<String,Object>());
}
public void put(String Key, Object cmsObject) {
ObjectCache.get(this.getClass()).put(key,cmsObject);
}
public Object get(String objectKey) {
return ObjectCache.get(this.getClass()).get(key);
}
}
答案 1 :(得分:1)
您的设计存在缺陷:
因此:
public class MyClass {
private static MyCache shortTermCache = new MyCache();
private static MyCache longTermCache = new MyCache();
}
您可以考虑将生存时间参数传递到缓存类构造函数中,以便在一段时间后管理清除。