SPI*_*984 3 java try-catch-finally
在我们的系统中,我们有一个抽象类,我们称之为BasicAction,它包含几个抽象方法.其中最重要的是执行.它处理来自JSP页面的请求.主处理程序的工作方式如下:
// Sample 1:
String actionName;// The name of action to use
Map<String, BasicAction> mapping;//The mapping of names and actual handlers
BasicAction action = mapping.get(actionName);
try {
action.execute(request);//Handle the http request from the JSP page
} catch (Exception ex) {
// Handle here any exceptions
}
Run Code Online (Sandbox Code Playgroud)
现在,一切看起来都很好,但基本上所有派生的处理程序都实现了相同的代码:
// Sample 1:
public class ConcreteAction extends BasicAction {
@Override
public void execute(HttpServletRequest request) {
// The managers provide the middle layer between
// web presentation and database
TrafficManager trafficManager = null;
CargoManager cargoManager = null;
try {
trafficManager = new TrafficManager();
cargoManager = new CargoManager();
// Perform here all the logic required using managers
} catch (Exception ex) {
// handle the exception or rethrow it
} finally {
// Should remove all managers clearly and release the connection
removeManager(trafficManager);
removeManager(cargoManager);
}
}
}
Run Code Online (Sandbox Code Playgroud)
在我拥有的每个处理程序中编写这样的块似乎有点烦人.似乎在这里我们模仿每个处理程序的输入/退出点而不是应该这样做.我认为我们需要的是在BasicAction中定义两个更抽象的方法,名为createManagers和disposeManagers.然后主处理程序将如下所示:
// Sample 2:
String actionName;// The name of action to use
Map<String, BasicAction> mapping;//The mapping of names and actual handlers
BasicAction action = mapping.get(actionName);
try {
action.createManagers(); // The enter point
action.execute(request);//Handle the http request from the JSP page
} catch (Exception ex) {
// Handle here any exceptions
} finally {
action.disposeManagers(); // The exit point
}
Run Code Online (Sandbox Code Playgroud)
之后,每个派生动作处理程序都可以这样定义:
// Sample 2:
public class ConcreteAction extends BasicAction {
private TrafficManager trafficManager = null;
private CargoManager cargoManager = null;
@Override
public void createManagers() {
trafficManager = new TrafficManager();
cargoManager = new CargoManager();
}
@Override
public void disposeManagers() {
removeManager(trafficManager);
removeManager(cargoManager);
}
@Override
public void execute(HttpServletRequest request) {
// Perform here all the logic required using managers
}
}
Run Code Online (Sandbox Code Playgroud)
哪种方法更好用 - 在每个处理程序中使用try-catch-finally或使用标准的进入/退出点.
| 归档时间: |
|
| 查看次数: |
1025 次 |
| 最近记录: |