Thursday, March 7, 2013

Template Method pattern in Java - Two Ways

In Java, there are two ways to implement Template Method pattern.  One is to use abstract method, another is to use anonymous inner class.  In the first way, you need to write an abstract base class.  In this abstract class, you should have at least one main public method.  This method is the main entry of your class and implement the main function.  At the same time, in this abstract class, you should add some abstract methods invoked by the main public method to make sub-classes to implement the details.

The second way is not the typical Template Method pattern.  But it can achieve the similar goal.  You can find a lot of examples from open source projects to use anonymous inner class to implement Template Method pattern.  One of famous examples is JdbcTemplate from Spring JDBC project.  In this class, the methods like execute(ConnectionCallback action) are using inner class to implement a template method.  The benefit using anonymous inner class to implement Template Method pattern is that you do not need to extends a base class.  So it is more flexible than the abstract class way.  But the con is you cannot enjoy the polymorphic type.

No comments:

Post a Comment