Java用户回调方法消除冗余代码
http://hi.baidu.com/luodaijun/blog/item/ce1cccef6acb173eadafd518.html
?
一. 看一段冗余的代码
public String login(HttpServletRequest request){
?? OperatorService operatorService = new OperatorService();
?? WebContext webContext= request.getSession().getAttribute("WEB_CONTEXT_KEY");
Connection conn=null;
try{
????? Conection conn =DBManager.getConnection();
?????? if(webContext.getOperatorName.equals("123")){
????????? // 登陆成功
????? }
}catch(Throwable t){
?? //记录日志
//跳转到统一的错误页面,不能让用户看到异常页面
?????? //关闭Connection
?????? if(conn!=null){
?????????? try{conn.close();}cath(SQLException ex){}
???? }
?? }
}
public String logOut(HttpServletRequest request){
?? OperatorService operatorService = new OperatorService();
?? WebContext webContext= request.getSession().getAttribute("WEB_CONTEXT_KEY");
try{
?????? Conection conn =DBManager.getConnection();
??????? operatorService.logout();
????? request.getSession().invalidate();
}catch(Throwable t){
?? //记录日志
//跳转到统一的错误页面,不能让用户看到异常页面
?????? //关闭Connection
?????? if(conn!=null){
?????????? try{conn.close();}cath(SQLException ex){}
???? }
?? }
}
二、可以看到,红色部分代码完全是冗余的,下面用回调方法简化这部分代码
1.先定义一个回调抽象类
public abstract class AppCallback {
??? /**
??? * 回调执行方法
??? *
??? * @return
??? */
??? public String execute() {
????? Connection conn=null;
?????? try{
?????????? conn= DBManager.getConnection();
??? ?? this.doLogic(conn);
??? ?? catch(Throwable t){
????????? //记录日志
?? //跳转到统一的错误页面,不能让用户看到异常页面
???????? //关闭Connection
???? if(conn!=null){
???????? try{conn.close();}cath(SQLException ex){}
???? ??? }
????? }
??? }
??? /**
??? * 业务代码,由子类实现
??? *
??? * @param xmlResponse
??? * @param webContext
??? */
??? public abstract void doLogic(Connection conn);
}
三、用回调类简化代码
public String login(HttpServletRequest request){
?? OperatorService operatorService = new OperatorService();
?? WebContext webContext= request.getSession().getAttribute("WEB_CONTEXT_KEY");
???? new AppCallback(){
????????? public void doLogic(Connection conn){
??????????????? // conn.executeQuery()
????????? }
??? }.execute();
}
public String logOut(HttpServletRequest request){
?? OperatorService operatorService = new OperatorService();
?? WebContext webContext= request.getSession().getAttribute("WEB_CONTEXT_KEY");
new AppCallback(){
????????? public void doLogic(Connection conn){
???????????????? // conn.executeQuery()
????????? }
??? }.execute();
}
当然,通过回调方法,约束并简化了代码,比如这里将异常捕捉逻辑封装起来,对程序编码也是一种规范,可以防止不好程序编写方式,比如忘记关闭Connection,把异常和关闭Connecton都放到回调类里,用户再也不必担心connection 的关闭了