自構建多級緩存

一、背景說明

        準備使用責任鏈模式,構建多級緩存鏈,依次逐級向下取值,直到取到值爲止。將取到的值再逐級賦值給未取到值的緩存級。

二、定義多級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);
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章