私たちのシステムには抽象クラスがあり、それをBasicActionと呼びましょう。これには、いくつかの抽象メソッドが含まれています。それらの中で最も重要なものはexecuteと呼ばれます。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
}
これで、すべてが正常に見えますが、基本的にすべての派生ハンドラーは同じコードを実装します。
// 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);
}
}
}
私が持っているすべてのハンドラーにそのようなブロックを書くのは少し面倒なようです。ここでは、各ハンドラーの入口/出口ポイントを想定どおりに模倣していないようです。ここで必要なのは、BasicActionでcreateManagersとdisposeManagersという2つの抽象メソッドを定義することだと思います。その場合、メインハンドラーは次のようになります。
// 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
}
その後、各派生アクションハンドラーは次のように定義できます。
// 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
}
}
どちらのアプローチを使用するのが良いか-各ハンドラーでtry-catch-finallyを使用するか、標準の入口/出口ポイントを使用します。