自构建多级缓存

一、背景说明

        准备使用责任链模式,构建多级缓存链,依次逐级向下取值,直到取到值为止。将取到的值再逐级赋值给未取到值的缓存级。

二、定义多级List

链路接口类Chain

public interface Chain {
   String get(String key );
}

缓存公用接口

public interface CacheClient {
   String get(Chain chain, String key);
}

缓存实现类

public class OneCacheClient implements CacheClient{
    private String get(String key){
	    //......
	}
	private String set(String key,String value){
	    //......
	}
	public String get(Chain chain, String key){
		String value = this.get(key);
		if(StringUtils.isBlank(key)){
			value = chain.get(key);
		}
		if(StringUtils.isBlank(key)){
			this.set(key,value);
		}
	}
}
public class TwoCacheClient implements CacheClient{
	private String get(String key){
	    //......
	}
	private String set(String key,String value){
	    //......
	}
	public String get(Chain chain, String key){
		String value = this.get(key);
		if(StringUtils.isBlank(key)){
			value = chain.get(key);
		}
		if(StringUtils.isBlank(key)){
			this.set(key,value);
		}
	}
}
public class ThreeCacheClient implements CacheClient{
	private String get(String key){
	    //......
	}
	private String set(String key,String value){
	    //......
	}
	public String get(Chain chain, String key){
		String value = this.get(key);
		if(StringUtils.isBlank(key)){
			value = chain.get(key);
		}
		if(StringUtils.isBlank(key)){
			this.set(key,value);
		}
	}
}

三、定义内部类

public class MultiCacheProxy {
	public static String get(List<CacheClient> list, String key ){
        return new DefaultChain(list).get(key);
    }
	private static class DefaultChain implements Chain {
		 private List<CacheClient> list = null;
		 private int i = -1;
		 public DefaultChain(List<CacheClient> list){
			   this.list = list;
		 }
		     @Override
                 public String get(String key) {
		     String  value = null;
		     i++;
			 if(i >= list.size()){
				return value;
			 }
			 CacheClient cache = list.get(i);
			 if(null != cache){
                          value = cache.get(this,key);
                          }
			 return value;
		 }
	}
}

四、测试类测试

public static void main(String[] args) {
	List<CacheClient> list = new ArrayList<>();
    list.add(new OneCacheClient());
    list.add(new TwoCacheClient());
    list.add(new ThreeCacheClient());
	String cacheKey = "Timer_bin_key"
    String value = YaoMultiCacheProxy.get(list,cacheKey);
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值