cometta
cometta

Reputation: 35689

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

Upvotes: 3

Views: 834

Answers (3)

cometta
cometta

Reputation: 35689

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

public abstract class BaseClass 
{      
  public Object executeTrans(Template template) 
  {
        // PersistenceManager pm = ...;
        Transaction tx = pm.currentTransaction();
        try {
            tx.begin();
             template.doTransaction();
            tx.commit();
        } finally {
            if (tx.isActive()) {
                tx.rollback();
            }
        }

  }
}

Upvotes: 1

Nick Holt
Nick Holt

Reputation: 34311

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.

Upvotes: 4

Michael Borgwardt
Michael Borgwardt

Reputation: 346317

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.

Upvotes: 1

Related Questions