Java用户回调方法消除冗余代码
一. 看一段冗余的代码
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){} } }}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();}