编程语言
首页 > 编程语言> > java – try-catch-finally vs抽象方法

java – try-catch-finally vs抽象方法

作者:互联网

在我们的系统中,我们有一个抽象类,我们称之为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
}

现在,一切看起来都很好,但基本上所有派生的处理程序都实现了相同的代码:

// 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.然后主处理程序将如下所示:

// 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或使用标准的进入/退出点.

解决方法:

就个人而言,我会采用抽象类方法,因为它是sounds like the Strategy pattern.而且,代码更清晰,更容易理解;加上 – 你不是一遍又一遍地重复这个结构.但这只是我的观点,有人可能会建议另一种方式.

标签:try-catch-finally,java
来源: https://codeday.me/bug/20190826/1734858.html