Java Vibes..

June 30, 2009

Template Pattern and Spring

Filed under: architecture & design — harjitdelhi @ 1:09 pm
Tags: , , , , ,

As you might be aware, Template is a GoF behavioral pattern. Here I first explain what the Template pattern is and then show an example of the pattern as implemented in the Spring framework:

Template works on the philosophy of Abstract classes, wherein the Abstract class implements some boiler plate functionality and let the subclasses implement the specifics.

For example, when you want to execute a JDBC query against a database, you have to implement the following steps:

  1. Obtain a DataSource
  2. Use the DataSource to get a Connection object
  3. Use the Connection object to create a Statement (or a PreparedStatement)
  4. Execute a query to get the ResultSet
  5. Iterate over the results and create a list of VOs (as an example of a business logic)
  6. Close the ResultSet
  7. Close the Statement
  8. Close the Connection

Out of the above steps, most of these are boiler plate code while steps #4 and #5 reflects the actual business logic. If you create a Template class (essentially an Abstract class) that models these steps and allow subclasses to customize the steps #4 and #5 then it will help subclasses reuse the boiler plate code.

Spring does this by providing classes like JdbcTemplate, HibernateTemplate, JmsTemplate etc.  Here is how things work in the Spring world:

template

Example code:
List results = getHibernateTemplate().executeFind(new HibernateCallback() {
                   public Object doInHibernate(Session session) {
                       Query query = session.createQuery("from Event");
                       query.setMaxResults(2);
                       return query.list();
                   }
});

Create a free website or blog at WordPress.com.