模板方法模式
如果我的 childClass 方法 getInfoFromDB() 和 saveToDB() 需要执行不同的逻辑,我可以知道如何创建 childClass 吗?
public abstract class BaseClass {
public abstract Object doTransaction();
public Object executeTrans() {
//do something
tx.begin();
this.doTransaction();
tx.commit();
}
}
public childClass extends BaseClass{
@Override
public Object doTransaction(){
//overide to get something from database so can only be used for getInfoFromDB() and not for saveToDB()
return something;
}
public List<String> getInfoFromDB(){
super.executeTrans();
}
public void saveToDB(){
super.executeTrans() ;
}
}
May i know how to create childClass if my childClass method getInfoFromDB() and saveToDB() need to do different logic?
public abstract class BaseClass {
public abstract Object doTransaction();
public Object executeTrans() {
//do something
tx.begin();
this.doTransaction();
tx.commit();
}
}
public childClass extends BaseClass{
@Override
public Object doTransaction(){
//overide to get something from database so can only be used for getInfoFromDB() and not for saveToDB()
return something;
}
public List<String> getInfoFromDB(){
super.executeTrans();
}
public void saveToDB(){
super.executeTrans() ;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在这种情况下,您应该使用模板模式,如下
所示: 话虽如此,我建议使用 Spring JDBC 模板类,而不是滚动您自己的 - 它们已经过尝试和测试,并且已经解决了您将遇到的问题嵌套事务等
You should use the template pattern in this case, something like this:
Saying that, I'd advise using the Spring JDBC template classes rather than rolling your own - they've been tried and tested and have solved the problems you'll run into with nested transactions etc.
将包含不同逻辑的 Runnable 传递给executeTrans() 方法。
但是,我不确定模板方法模式是否真的是您所需要的(以及它如何处理回滚?)。您可能想研究一个框架,例如 Spring,它允许 声明式交易。
Pass a Runnable containing the different logic to the executeTrans() method.
However, I'm not sure the template method pattern is really what you need here (and how is it handling rollbacks?). You may want to look into a framework such as Spring that allows declarative transactions.
缺口,
我要使用的“tx”如下所示。从代码来看,最佳实践是生命周期正常,因为它是由 savetodb() 和 getinfofromdb() 调用的
Nick,
the "tx" that i going to use look like below. judging from the code, best practise, is the lifecycle is ok since it's called by both savetodb() and getinfofromdb()