如果我的 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() ;
}
}
最佳答案
在这种情况下你应该使用模板模式,像这样:
public abstract class BaseClass
{
public Object executeTrans(Template template)
{
tx.begin();
template.doTransaction();
tx.commit();
}
}
public interface Template
{
public void doTransaction();
}
public childClass extends BaseClass
{
public List<String> getInfoFromDB()
{
executeTrans(
new Template()
{
public void doTransaction()
{
...do get info from DB here.
}
}
);
}
public void saveToDB()
{
executeTrans(
new Template()
{
public void doTransaction()
{
...do save to DB here.
}
}
);
}
}
话虽如此,我建议您使用 Spring JDBC 模板类而不是自己动手 - 它们已经过尝试和测试,并且已经解决了您将在嵌套事务等方面遇到的问题。
关于java - 模板方法模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1276624/