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

Posted 一乐乐

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了重复动作要封装,封装前找大家的共同特性或者说共同需求(例如都实现某个接口,都实现该接口的某个方法),然后利用这个共同特性封装起来相关的知识,希望对你有一定的参考价值。

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

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

 

具体举例子:例如方法执行到最后,要关闭各自资源:像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) { 

  Object.nonNull(autoCloseable)         autoCloseble.close();

}

 

以上是关于重复动作要封装,封装前找大家的共同特性或者说共同需求(例如都实现某个接口,都实现该接口的某个方法),然后利用这个共同特性封装起来的主要内容,如果未能解决你的问题,请参考以下文章

面向对象4大特性

Java继承2

面向对象编程基本部分——java三大特性详解

春哥博客

面向对象——浅谈弊端

Android图片加载库的封装实战之路