JAVA自定义通用缓存

1,缓存基类
public abstract class BaseCache<T> {
 static Map<String, Map<String, ?>> _map = new HashMap<String, Map<String, ?>>();
 
 @SuppressWarnings("rawtypes")
 static List<BaseCache> _list = new ArrayList<BaseCache>();
 
 protected void add(String key, Map<String, T> value){
  _map.put(key, value);
 }
 
 protected void remove(String key){
  _map.remove(key);
 }
 
 protected HashMap<String, T> getMap(String key){
  return (HashMap<String, T>) _map.get(key);
 }
 
 protected boolean containsKey(String key){
  return _map.containsKey(key);
 }
 
 protected static void registCache(BaseCache cache){
  _list.add(cache);
 }
 
 protected  abstract Map<String, T> readData();
 
 public abstract HashMap<String, T> getObject();
 
 public abstract T getValue(String key);
 
 public abstract void refresh();
 
 public abstract void refreshValue(String key, T value);
 
 public static void loadAllData(){
  for(BaseCache bc : _list){
   bc.refresh();
  }
 }
 
}
 
2,一个子类实例
public class SystemArgsCache extends BaseCache<String> {
 
 private static final String CACHE_KEY = "SystemArgs";
 
 private static SystemArgsCache propertiesCache = new SystemArgsCache();
 
 static{
  registCache(propertiesCache);
 }
 
 private SystemArgsCache(){
 }
 
 public static SystemArgsCache getInstance(){
  if(propertiesCache == null){
   synchronized (SystemArgsCache.class) {
    if(propertiesCache == null){
     propertiesCache = new SystemArgsCache();
    }
   }
  }
  return propertiesCache;
 }
 
 private synchronized void addChannelCache(){
  add(CACHE_KEY, readData());
 }
 @Override
 protected Map<String, String> readData() {
  Map<String, String> map = new HashMap<String, String>();
  map.put("a", "a");
  map.put("b", "b");
  return map;
 }
 @Override
 public HashMap<String, String> getObject() {
  if(!containsKey(CACHE_KEY)){
   addChannelCache();
  }
  return getMap(CACHE_KEY);
 }
 @Override
 public String getValue(String key) {
  return getObject().get(key);
 }
 @Override
 public void refresh() {
  addChannelCache();
 }
 @Override
 public void refreshValue(String key, String value) {
  HashMap<String, String> map = getObject();
  map.put(key, value);
 }
}


参考资料:http://hi.baidu.com/lya_loveme/blog/item/382a9e20167f1051ac34dedc.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值