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();
    }
  • 相关阅读:
    idea找不到或无法加载主类
    Scala核心编程_第09章 面向对象编程(高级特性)
    spring源码:学习线索
    Redis
    spring源码:Aware接口
    spring源码:核心组件(li)
    java socket编程
    spring源码:ApplicationContext的增强功能(li)
    spring源码:web容器启动
    spring源码:BeanPostProcessor(li)
  • 原文地址:https://www.cnblogs.com/shan333/p/14889902.html
Copyright © 2011-2022 走看看