1.假设有如下的业务方法类:
import java.util.Map;
/**
* 业务方法
* @author yaol
*
*/
public class TestService {
BaseDao dao = new BaseDao();
public Object findById(Map params){
/**
* 检测参数
*/
Object obj =null;
String id = null;
try{
id = (String)params.get("id");
}
catch(Exception e){
e.printStackTrace();
return error();
}
/**
* 获取结果
*/
try{
obj = dao.findById(id);
return ok();
}
catch(Exception e){
e.fillInStackTrace();
return error();
}
}
public Object findByPage(Map params){
Object obj =null;
int pageNo,pageSize;
/**
* 检测参数
*/
try{
pageNo =(Integer) params.get("pageNo");
pageSize = (Integer)params.get("pageSize");
}
catch(Exception e){
e.printStackTrace();
return error();
}
/**
* 获取结果
*/
try{
obj = dao.findByPage(pageNo, pageSize);
return ok();
}
catch(Exception e){
e.fillInStackTrace();
return error();
}
}
public Object error(){
return "error";
}
public String ok(){
return "ok";
}
}
/**
* Dao
* @author yaol
*
*/
class BaseDao{
public Object findById(String id){return null;}
public Object findByPage(int pageNo,int pageSize){return null;}
}
应该可以看出findById和findByPage结构是完全相同的.
先校验参数合法性,再根据参数获取结果,并且分别做异常处理.
如果业务方法增加的话,程序中会充斥了大量的异常处理代码.
如何减少这些重复的异常处理代码呢?
2.引入模板模式和回调接口
代码如下:
/**
* 回调接口
* @author yaol
*
*/
interface ServiceCallback {
/**
* 验证参数合法性以及设置参数
* @param map
*/
public void checkAndSetParamters();
/**
* 获取数据
* @param map
* @return TODO
*/
public Object getResult() throws Exception;
}
/**
* 业务模板
* @author yaol
*
*/
public class ServiceTemplate {
public Object execute(ServiceCallback callback) {
try {
callback.checkAndSetParamters();
} catch (Exception e) {
e.printStackTrace();
return error();
}
try {
Object obj = callback.getResult();
return ok();
} catch (Exception e) {
e.fillInStackTrace();
return error();
}
}
public Object error() {
return "error";
}
public String ok() {
return "ok";
}
}
3.改写业务方法类
/**
* 改写后的业务方法类
* @author yaol
*
*/
public class TestService2 extends ServiceSupport{
public Object findByPage(final Map params) {
return getServiceTemplate().execute(new ServiceCallback() {
int pageNo, pageSize;
public void checkAndSetParamters() {
pageNo = (Integer) params.get("pageNo");
pageSize = (Integer) params.get("pageSize");
}
public Object getResult() throws Exception {
return getDao().findByPage(pageNo, pageSize);
}
});
}
public Object findById(final Map params) {
return getServiceTemplate().execute(new ServiceCallback() {
String id = null;
public void checkAndSetParamters() {
id = (String)params.get("id");
}
public Object getResult() throws Exception {
return getDao().findById(id);
}
});
}
public BaseDao getDao() {
return new BaseDao();
}
}
/**
* ServiceSupport
* @author yaol
*
*/
class ServiceSupport{
public ServiceTemplate getServiceTemplate() {
return new ServiceTemplate();
}
}
/*
这里的ServiceSupport和Spring提供的XXXDaoSupport相似,而getServiceTemplate()类似于getHibernateTemplate()方法.
阅读优秀的开源代码对程序员是大有裨益的.
*/