Search code examples
javaspringtemplate-method-pattern

template method pattern


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() ;
    }
}

Solution

  • You should use the template pattern in this case, something like this:

    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.
            }
          }
        );
      }
    }
    

    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.