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

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

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

    具体举例子:例如方法执行到最后,要关闭各自资源:像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();
    }
  • 相关阅读:
    Bzoj1597 [Usaco2008 Mar]土地购买
    Bzoj1500 [NOI2005]维修数列
    模拟7 题解
    模拟6 题解
    模拟5 题解
    远古杂题 2
    远古杂题 1
    [NOIP2013]华容道 题解
    奇袭 CodeForces 526F Pudding Monsters 题解
    图论杂题
  • 原文地址:https://www.cnblogs.com/shan333/p/14889902.html
Copyright © 2011-2022 走看看