package org.test.spring.template;
/**
* 基于继承的模版设计模式!
* @author asus_n56
*
*/
public abstract class MytemplateByIn {
private void beginConnection(){
System.out.println("开始连接!");
}
private void closeConnection(){
System.out.println("关闭连接!");
}
public abstract void run();
public abstract boolean validateRun();
public void execute(){
this.beginConnection();
if (this.validateRun()) {
this.run();
}
this.closeConnection();
}
}
package org.test.spring.template;
public class RoleDao extends MytemplateByIn {
private MytemplateByZuHe mytemplateByZuHe = new MytemplateByZuHe();
public void add(int id) {
mytemplateByZuHe.add(id);
}
public void delete(int id) {
mytemplateByZuHe.delete(id);
}
/**
* 上面是zuhe实现,下面是继承实现
*/
@Override
public void run() {
System.out.println("这是执行的run()");
}
@Override
public boolean validateRun() {
return true;
}
}
package org.test.spring.template;
/**
* 模版设计模式的组合实现
* @author asus_n56
*
*/
public class MytemplateByZuHe {
private void beginConnection(){
System.out.println("开始连接!");
}
private void closeConnection(){
System.out.println("关闭连接!");
}
/**
* 调用方法,传入一个钩子函数的的接口
*/
public void execute(MyCallBack myCallBack){
this.beginConnection();
myCallBack.doInTempletate();
this.closeConnection();
}
/**
* 所有要实现的方法都在模版中建立
*/
public void add(final int id) {
this.execute(new MyCallBack() {
@Override
public void doInTempletate() {
System.out.println("添加了某某!+"+id);
}
});
}
public void delete(final int id) {
this.execute(new MyCallBack() {
@Override
public void doInTempletate() {
System.out.println("删除了+"+id);
}
});
}
}
package org.test.spring.template;
import org.junit.Test;
public class RoleDaoTest {
private RoleDao roleDao = new RoleDao();
private MessageDao messageDao = new MessageDao();
@Test
public void testRun() {
roleDao.execute();
}
@Test
public void testMessage(){
messageDao.execute();
}
@Test
public void testZuHe(){
roleDao.add(100);
}
}