无论是Thread本身run方法,还是Runable的run方法,都是想将线程的控制本身和业务逻辑的运行分离开来,达到职责分明、功能单一的原则,这点和GoF中的策略模式相似。
下面模拟jdbc开发,将数据的封装部分抽取成一个策略接口
public interface RowHandler<T> {
T handler(ResultSet rs);
}
public class RecordQuery {
private final Connection connection;
public RecordQuery(Connection connection) {
this.connection = connection;
}
public <T> T query(RowHandler<T> rowHandler,String sql,Object... params) throws SQLException {
try (PreparedStatement statement = connection.prepareStatement(sql)) {
int index = 1;
for(Object o:params){
statement.setObject(index++,o);
}
ResultSet resultSet = statement.executeQuery();
return rowHandler.handler(resultSet);
}
}
}
说明:RecordQuery只负责数据的查询,RowHandler负责数据的加工,至于加工成什么样,根据传入的参数决定。
职责分明,每个类功能单一。这类似于Thread与Runable之间的关系。