现在的位置: 首页 > 综合 > 正文

模板方法设计模式(JDBCTeampleta

2012年01月07日 ⁄ 综合 ⁄ 共 2143字 ⁄ 字号 评论关闭

 问题的由来:我们一般的如果不用spring的templeta,我们连接数据库的方法是:Connection ,Statement ,ResultSet ......等等

 
但是如果我们打开jdbcTempleta来看,其实我们是用了模板设计模式来封装了。
模板设计模式指的是将相应的模板方法(其中也就是重复的代码)提取出来在专门的一个位置定义,然后把相同调用过程的操作,通过模板来实现 对于模板设计模式而言,一般有两种方式 1、基于继承的实现
 
eg:
//抽象类
package org.zttc.itat.template;
 
/**
 * 基于继承实现模板设计模式
 * @author Administrator
 *
 */
public abstract class MyJdbcTemplateByIn {
 
private void beginConnection() {
System.out.println("begin connection");
}
 
private void closeConnection() {
System.out.println("close connection");
}
 
public abstract void run();
/**
 * 在模板方法中有一种函数叫做钩子函数,钩子函数的作用是让实现类可以通过一些方法来控制模板中的流程
 * @return
 */
public abstract boolean isLog();
 
public void execute() {
beginConnection();
if(isLog()) {
System.out.println("加入了日志");
}
run();
closeConnection();
}
}
//实现类
 
package org.zttc.itat.template;
 
public class RoleDao extends MyJdbcTemplateByIn {
 
private MyJdbcTemplate mt = new MyJdbcTemplate();
 
public void add(int id){
mt.add(id);
}
 
public void delete(int id) {
mt.delete(id);
}
 
@Override
public void run() {
System.out.println("role add");
}
 
@Override
public boolean isLog() {
return false;
}
 
}
 
 
2、基于组合的实现
 
 
//钩子函数的接口,这里的例子 让我知道接口不一定要用来继承或者实现(iplenments),还可以作为参数。
package org.zttc.itat.template;
 
public interface MyCallback {
public void doInTemplate();
}
 
package org.zttc.itat.template;
 
public class MyJdbcTemplate {
 
private void beginConnection() {
System.out.println("begin connection");
}
 
private void closeConnection() {
System.out.println("close connection");
}
/**
 * 调用方法,传入一个钩子函数的接口,通俗一点理解就是:把一个抽象类作为参数,在方法体中调用它的方法,这样 在调用这个方法的时候你可以实现它,相当于你开了一个空头支票,他在一个时间会使用,但是随便你自己填写金额。      
 */
public void execute(MyCallback call) {
beginConnection();
call.doInTemplate();
closeConnection();
}
 
/**
 * 将所有要实现的方法都创建在模板中
 */
 
 
//大大的疑问:为什么这里要用静态参数
 
public void add(final int id) {
execute(new MyCallback() {
@Override
public void doInTemplate() {
System.out.println("add:"+id);
}
});
}
 
public void delete(final int id) {
execute(new MyCallback() {
 
@Override
public void doInTemplate() {
System.out.println("delete:"+id);
}
});
}
}
 
 
package org.zttc.itat.template; public class RoleDao extends MyJdbcTemplateByIn { private MyJdbcTemplate mt = new MyJdbcTemplate(); public void add(int id){ mt.add(id); } public void delete(int id) { mt.delete(id); } @Override public void run() { System.out.println("role add"); } @Override public boolean isLog() { return false; } }
 

抱歉!评论已关闭.