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