Template Method模式的应用场景是:
1. 你想将相同的算法放在一个类中,将算法变化的部分放在子类中实现。
2. 子类公共的算法应该放在一个公共的类中,避免代码重复。
Template Method模式可以限制所留下的虚方法只对其继承类可见,外部使用者不一定能够直接使用这些虚方法。
下面是示例代码:
public abstract class BaseDao {
/**
* 增,删,改方法
* @param sql
* @param args sql参数
* @return
* @throws DaoException
*/
public int update(String sql, Object[] args) throws DaoException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection();
ps = conn.prepareStatement(sql);
for (int i = 0; i < args.length; i++)
ps.setObject(i + 1, args[i]);
return ps.executeUpdate();
} catch (SQLException e) {
throw new DaoException(e.getMessage(), e);
} finally {
JdbcUtils.free(rs, ps, conn);
}
}
/**
* 返回一个对象
* @param <T>
* @param sql
* @param args
* @return
* @throws DaoException
*/
public <T> T find(String sql, Object[] args) throws DaoException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection();
ps = conn.prepareStatement(sql);
for (int i = 0; i < args.length; i++)
ps.setObject(i + 1, args[i]);
rs = ps.executeQuery();
T t = null;
if (rs.next()) {
t = rowMapper(rs);
}
return t;
} catch (SQLException e) {
throw new DaoException(e.getMessage(), e);
} finally {
JdbcUtils.free(rs, ps, conn);
}
}
/**
* 返回一个List
* @param <T>
* @param sql
* @param args
* @return
* @throws DaoException
*/
public <T> List<T> list(String sql, Object[] args) throws DaoException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection();
ps = conn.prepareStatement(sql);
for (int i = 0; i < args.length; i++)
ps.setObject(i + 1, args[i]);
rs = ps.executeQuery();
T t = null;
List<T> list = new ArrayList<T>();
while (rs.next()) {
t = rowMapper(rs);
list.add(t);
}
return list;
} catch (SQLException e) {
throw new DaoException(e.getMessage(), e);
} finally {
JdbcUtils.free(rs, ps, conn);
}
}
/**
* rowMapper
* @param rs
* @return
* @throws DaoException
*/
abstract protected <T> T rowMapper(ResultSet rs) throws DaoException;
}
实现类的代码:
public class UserDaoImpl extends BaseDao implements UserDao {
public User findUser(int id) throws DaoException {
String sql = "select *from t_user where id=?";
Object[] args = new Object[] { id };
User user = super.find(sql, args);
return user;
}
public List<User> listUser(String username) throws DaoException {
String sql = "select *from t_user where username=?";
Object[] args = new Object[] { username };
List<User> list = super.list(sql, args);
for (User u : list) {
System.out.println(u.getUserId());
}
return list;
}
@SuppressWarnings("unchecked")
protected User rowMapper(ResultSet rs) throws DaoException {
User user = new User();
try {
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setBrithday(rs.getDate("brithday"));
} catch (SQLException e) {
throw new DaoException(e.getMessage(), e);
}
return user;
}