我有一个应用程序,我需要两个静态缓存,一个是短期缓存,一个是长期缓存。
所以我有一个抽象类,看起来像这样。 我的想法是,我将创建两个继承自此抽象类的类,从而获得我的两个静态类。
但是,我突然想到,当我可能能够使用一个对象时,我正在创建 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) {
//
}
}
你的设计有缺陷:
- 缓存
- 就是缓存 - 让缓存类负责缓存...只
- 除非对象数量很大(1000个),否则不要让"创建的对象数量"影响您的设计
- 只有缓存类的用户需要知道或关心缓存的使用方式
因此:
public class MyClass {
private static MyCache shortTermCache = new MyCache();
private static MyCache longTermCache = new MyCache();
}
可以考虑将生存时间参数传递到缓存类构造函数中,以使其管理特定时间后的清除。
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);
}
}