-
一次重构
2004-04-13
版权声明:转载时请以超链接形式标明文章原始出处和作者信息及本声明
http://piginzoo.blogbus.com/logs/138062.html
重构了DictionaryService,开始的时候,
Dictonary的接口如下:
public List getDictionary(String rootCode,HttpServletRequest request){
return this.getDictionary(rootCode,request.getSession());
}
public List getDictionary(String rootCode,HttpSession session){
return this.getDictionary(rootCode,session.getServletContext());
}
public List getDictionary(String rootCode,ServletContext context){
HashMap dictionaryMap = getDictionary(context);
List list = (List)dictionaryMap.get(rootCode);
if(list==null){
list = facade.findDictionaryListByCategoryByCode(rootCode);
dictionaryMap.put(rootCode,list);
log.info("系统数据字典[" + rootCode + "]被初始化");
}
return list;
}
但是写单元测试的时候,就感觉十分不方便了,我怎么去构造request,session,context呀?
于是开始重构:
private ICacheContainer cache;
public DictionaryService(ICacheContainer cache){
this.cache = cache;
}
public List getDictionary(String rootCode)
HashMap dictionaryMap = getDictionary(cache);
List list = (List)dictionaryMap.get(rootCode);
if(list==null){
list = facade.findDictionaryListByCategoryByCode(rootCode);
dictionaryMap.put(rootCode,list);
log.info("系统数据字典[" + rootCode + "]被初始化");
}
return list;
}
重构後,构造函数引入ICacheContainer,代替了request,session,context
WebCacheContainer 是 ICacheContainer 的一个实现:
public class WebCacheContainer implements ICacheContainer {
private ServletContext context;
public WebCacheContainer(ServletContext context){
this.context = context;
}
public WebCacheContainer(HttpServletRequest request){
this(request.getSession());
}
public WebCacheContainer(HttpSession session){
this(session.getServletContext());
}
public void put(String key, Object obj) {
context.setAttribute(key,obj);
}
public Object get(String key) {
return context.getAttribute(key);
}
}
在调用的时候,这样使用
private DictionaryService getDictionaryService(HttpServletRequest request){
if (service == null) {
service = new DictionaryService(new WebCacheContainer(request));
}
return service;
}
。。。。
//同步缓冲
this.getDictionaryService(request).updateDictionary(dictionary.getCode()//-- 测试代码如下:--
public class DictionaryServiceTest extends TestCase {
final public void testGetDictionary() {
DictionaryService service = new DictionaryService(
new ICacheContainer(){
private HashMap hashMap = new HashMap();
public void put(String key,Object obj){
hashMap.put(key,obj);
}
public Object get(String key){
return hashMap.get(key);
}
}
);
List list = service.getDictionary("document_type");
for(int i=0;i<list.size();i++){
DictionaryBO dictionary = (DictionaryBO)list.get(i);
Debug.printTree(dictionary);
}
}}
收藏到:Del.icio.us







