Template method design pattern

This is another very important design pattern in Java and another core design pattern which is used in Spring framework.Template method design pattern is a behavioral design pattern. This is used to define a the flow of execution of the application.

Just think you need to build a building. Then you should begin it with foundation. You can't begin it with the roof. Likewise you can define the flow using this design pattern. 

Look at the following example. 

Here you can see three classes. If you going to build a office building, it will be done in certain way. This flow cannot be changed. So if you want to create another building, you can do the same way. 

As you can see, the template method is final. That is why it cannot be changed. Look at the following class diagram for two buildings.

When it uses ?
  • javax.servlet.http.HttpServlet doGet() and doPost() methods.
  • In Spring framework - In Spring framework, it uses so many templates. These templates are created based on template method design pattern. 
  • All non abstract methods of followings
    1. java.io.InputStream
    2. java.io.OutputStream
    3. java.io.Reader
    4. java.io.Writer 

  • All non abstract methods in followings too.
    1. java.util.AbstractList
    2. java.util.AbstractSet
    3. java.util.AbstractMap
  • JDBC template uses this design pattern - In JDBC template we don't need to care about the open, close connections and so on. This is automatically done by the template itself. It executes the core workflow, we don't need to manage it. 

Template method design pattern Template method design pattern Reviewed by Ravi Yasas on 3:34 PM Rating: 5

No comments:

Powered by Blogger.