nicolas 111008
一、介绍
Spring通过参数化资源和模板方法将资源与业务代码分离,利用这种方式可以对资源进行统一管理。
二、主要操作
1)抽取业务代码共性,业务代码直接使用资源。
2)通用代码维护资源,调用业务共性方法。
3)编写具体业务代码负责资源操作相关的各种具体业务,封装后,调用者可摆脱资源维护代码。
三、示例
代码剪切自Spring
1. 建立资源操作接口
抽取业务共性
public interface ClientCallback { Object doInClient(Executor executor) throws SQLException; }
2. 封装资源获取和释放
维护资源,只和共性业务有关。
public Object execute(ClientCallback action) throws DataAccessException { Executor session = this.sqlMapClient.openSession(); try { return action.doInClient(session); } catch (SQLException ex) { throw ExceptionTranslator().translate("Operation", ex); } if (session != null) { session.close(); } }
3. 具体业务代码
通过参数化资源,不再承担资源的维护责任。进一步封装后,调用者完全和资源无关。
public Object queryForObject(String statementName, Object parameterObject) throws DataAccessException { return execute(new ClientCallback() { public Object doInClient(Executor executor) throws SQLException { return executor.queryForObject(statementName, parameterObject); } }); }
此处的真正具体业务代码为executor.queryForObject