简介
行为型模式:控制逻辑
结构型模式:代码结构改动
创建型模式:创建对象
委派模式
又叫委托模式,它的基本作用是负责任务的分配和调用,是一种特殊的静态代理,可以理解为全权代理,属于行为型模式,不属于GOF23种设计模式。
模板方法模式
模板方法模式是指定义一个操作中的算法的框架,而将一些步骤延迟到子类中,使得子类可以不改变算法的结构即可重新定义该算法的某些特定步骤,属于行为型模式。
简单jdbcTemplate的应用:
public interface RowMapper<T> {
T mapRow(ResultSet rs, int rowNum) throws Exception;
}
public abstract class JdbcTemplate {
private DataSource dataSource;
public JdbcTemplate(DataSource dataSource) {
this.dataSource = dataSource;
}
public final <T> List<T> executeQuery(String sql,RowMapper<T> rowMapper,Object[] values){
try {
//1、获取连接
Connection conn = this.getConnection();
//2、创建语句集
PreparedStatement pstm = this.createPrepareStatement(conn,sql);
//3、执行语句集
ResultSet rs = this.executeQuery(pstm,values);
//4、处理结果集
List<T> result = this.parseResultSet(rs,rowMapper);
//5、关闭结果集
rs.close();
//6、关闭语句集
pstm.close();
//7、关闭连接
conn.close();
return result;
}catch (Exception e){
e.printStackTrace();
}
return null;
}
private <T> List<T> parseResultSet(ResultSet rs, RowMapper<T> rowMapper) throws Exception {
List<T> result = new ArrayList<>();
int rowNum = 0;
while (rs.next()){
result.add(rowMapper.mapRow(rs,rowNum++));
}
return result;
}
private ResultSet executeQuery(PreparedStatement pstm, Object[] values) throws SQLException {
for (int i = 0; i < values.length; i++) {
pstm.setObject(i + 1,values[i]);
}
return pstm.executeQuery();
}
private PreparedStatement createPrepareStatement(Connection conn, String sql) throws SQLException {
return conn.prepareStatement(sql);
}
private Connection getConnection() throws SQLException {
return this.dataSource.getConnection();
}
}
@Data
public class Member {
private String username;
private String password;
private String nickname;
private int age;
private String addr;
}
public class MemberDao extends JdbcTemplate {
public MemberDao(DataSource dataSource) {
super(dataSource);
}
public List<Member> selectAll(){
String sql = "select * from t_member";
return super.executeQuery(sql, (rs, rowNum) -> {
Member member = new Member();
//字段过多,原型模式
member.setUsername(rs.getString("username"));
member.setPassword(rs.getString("password"));
member.setAge(rs.getInt("age"));
member.setAddr(rs.getString("addr"));
return member;
},null);
}
}
总结
模板方法模式:(父类)固定流程、(子类)细节微调