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();
    }
  • 相关阅读:
    奶酪工厂
    P1080 国王游戏(非高精版)
    【洛谷P2150】[NOI2015] 寿司晚宴
    【洛谷P3349】[ZJOI2016]小星星
    【洛谷P5785】[SDOI2012]任务安排
    【模板】严格次短路
    【洛谷P3647】[APIO2014]连珠线
    2021.10.27NOIP模拟总结
    【树形DP】CF1016F Road Projects
    2021CSP-S 总结
  • 原文地址:https://www.cnblogs.com/shan333/p/14889902.html
Copyright © 2011-2022 走看看