重复动作要封装,封装前找大家的共同特性或者说共同需求(例如都实现某个接口,都实现该接口的某个方法),然后利用这个共同特性封装起来

重复动作要封装,封装前找大家的共同特性或者说共同需求(例如都实现某个接口,都实现该接口的某个方法),

然后利用这个共同特性封装起来

具体举例子:例如方法执行到最后,要关闭各自资源:像ResultSet,Statement,PreparedStatement,Connection都需要关闭。

且关闭前都需要先判断是否为空,然后非空再关闭!

原来代码书写:

public void close(ResultSet resultSet, Statement statement, PreparedStatement preparedStatement, Connection connection){
          if(resultSet != null)                  resultSet.close();
          if(statement != null)                  statement.close();
          if(preparedStatement != null)          preparedStatement.close();
          if(connection != null)                 connection.close();

}

再封装一下代码:点击ResultSet进去,发现它之所以可以直接调用close() 方法, 是因为它实现了接口 AutoCloseable,AutoCloseable 接口定义了close()方法.同理StatementPreparedStatement等等也是这样的。

所以咱定义一个free(参数是接口AutoCloseable autoCloseable) { 

  if(Objects.nonNull(autoCloseable))
autoCloseable.close();
}
原文地址:https://www.cnblogs.com/shan333/p/14889902.html