Template Method Design Pattern


Published on

Template method design pattern is quite useful for framework designers as it provides a mechanism for users of framework to extend the framework.

Published in: Technology, Business
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Template Method Design Pattern

  1. 1. Template Method Pattern ~ Mother of all frameworks ~ Srikanth P Shreenivas [email_address] http://www.srikanthps.com
  2. 2. Game Console for playing Pool Slide public class Pool { aTypicalGamingSession() { startup(); retrieveLastSavedState(); displayPoolTable(); while (not exit) { acceptUserInput(); redrawTheTable(); } printWinner() saveUserScore; updateHighScores; } }
  3. 3. Game Console – More games Slide <ul><li>public class Game { </li></ul><ul><li>aTypicalGamingSession() { </li></ul><ul><li>startup(); </li></ul><ul><li>retrieveLastSavedState(); </li></ul><ul><li>if (game == pool); </li></ul><ul><li> displayPoolTable(); </li></ul><ul><li>if (game == chess); </li></ul><ul><li> displayChessBoard(); </li></ul><ul><li>while (not exit) { </li></ul><ul><li> acceptUserInput(); </li></ul><ul><ul><ul><li>if (game == pool); </li></ul></ul></ul><ul><ul><ul><li>reCalculatePositionOfBalls(); </li></ul></ul></ul><ul><ul><ul><li>if (game == chess); </li></ul></ul></ul><ul><ul><ul><li>reCalculatePositionsOfPawns(); </li></ul></ul></ul><ul><li>} </li></ul><ul><li>printWinner() </li></ul><ul><li>saveUserScore; </li></ul><ul><li>updateHighScores; </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  4. 4. Game Console – What’s common? Slide <ul><li>Every game has following sequence </li></ul><ul><ul><li>User login </li></ul></ul><ul><ul><li>Retrieve last saved state. </li></ul></ul><ul><ul><li>Display the game. </li></ul></ul><ul><ul><li>React to user controls. </li></ul></ul><ul><ul><li>Save the game state. </li></ul></ul><ul><ul><li>Print winner </li></ul></ul>Game startGame() { retrieveLastSavedState(); displayGame(); while (not exit) { reactToUserControl(); } saveGame(); printWinner(); } Abstract displayGame(); Abstract reactToUserControl(); Delegate game specific behavior to derived classes, while controlling the main game behavior in base class. Common Behavior Game-specific Behavior Chess displayGame() { displayChessBoard(); } reactToUserControl() { moveThePiece(); } Pool displayGame() { displayPoolTable(); } reactToUserControl() { strikeWithCueBall(); }
  5. 5. Template Method Pattern Slide <ul><li>Template method defines the steps of an algorithm, and allows subclasses to provide an implementation of one or more steps. </li></ul><ul><li>The template method is used for: </li></ul><ul><li>letting subclasses implement behavior that can vary </li></ul><ul><li>avoiding duplication in the code: you look for the general code in the algorithm, and implement the variants in the subclasses </li></ul><ul><li>controlling at what point(s) sub-classing is allowed. </li></ul>ConcreteClass 2 step1() { } step3OptionalStep() { //diff. implementation } Algorithm() { step1(); step2MustAlwaysDoThis(); step3OptionalStep(); step4finalStep(); } Abstract step1(); Final step2MustAlwaysDoThis() { } step3OptionalStep() { //Default code } Final step4FinalStep() { } Base Class ConcreteClass 1 step1() { }
  6. 6. Inversion of control <ul><li>Game class calls the method of sub-classes, thus, telling the sub-classes – “Don’t call me, I will call you” </li></ul><ul><li>Template method enforces “Open Closed Principle” – A class should be open for extension, but closed for modification” </li></ul>Slide Hollywood Principle <ul><li>Inversion of Control </li></ul><ul><li>A key differentiator between frameworks and libraries </li></ul><ul><li>Framework invokes your code. </li></ul><ul><li>You invoke library’s code. </li></ul>
  7. 7. Servlets – A case study for IoC <ul><li>Life Cycle </li></ul><ul><ul><li>init() </li></ul></ul><ul><ul><li>service() </li></ul></ul><ul><ul><li>destroy() </li></ul></ul><ul><li>service() method is an abstract method in “GenericServlet” class. </li></ul><ul><li>HttpServlet is a sub-class of “GenericServlet”. </li></ul><ul><li>HttpServlet implements “service()” method. </li></ul><ul><li>Based on HTTP request type, HttpServlet invokes </li></ul><ul><ul><li>doGet, doPost, doHead, doPut, doDelete(), doOptions(), doTrace(). </li></ul></ul><ul><li>HttpServlet’s service method defines a template for handling HTTP requests, it calls the right methods at right time. </li></ul><ul><li>Developers extend HttpServlet and write meaninful implementation of doGet, doPost, etc. </li></ul>Slide
  8. 8. Servlets – IoC and Template Method Pattern <ul><li>We don’t control when our code is invoked. </li></ul><ul><li>Servlet container invokes our servlet’s code. </li></ul><ul><li>HttpServlet defines a template method , service(), which takes care of general purpose handling of HTTP requests by calling doGet, doPost… </li></ul><ul><li>We can extend HttpServlet by overriding the steps of the algorithm, doGet and doPost methods, to provide meaningful results. </li></ul>Slide Servlet Container’s Hollywood Principle: Don’t call me, I will call you (servlet) !!! (whenever I hear from a browser) Servlet’s Template Method: Let me have the control of algorithm and let me deal with HTTP, you (Developer) just respond with some meaningful action when I call your methods.
  9. 9. “ Mother of all frameworks”….How? <ul><li>All frameworks implement some kind of “Inversion of Control”. </li></ul><ul><ul><li>Examples: Servets, EJBs, Web Service Frameworks, Spring </li></ul></ul><ul><li>Frameworks, which depend on application to extend it by sub-classing some of its classes, uses template method pattern. </li></ul><ul><ul><li>Servlet’s doGet and doPost methods </li></ul></ul><ul><li>Frameworks which allow applications to get involved at critical points (starting of transaction, object initialization) provide hooks which can be implemented by application. This again requires use template method pattern. </li></ul><ul><ul><li>MDB’s onMessage method </li></ul></ul>Slide
  10. 10. Ways of Extending Classes (and Frameworks) <ul><li>Inheritance </li></ul><ul><ul><li>Use template method design pattern when you need to extend using inheritance </li></ul></ul><ul><li>Composition </li></ul><ul><ul><li>Use Strategy design pattern when you want to extend using composition </li></ul></ul>Slide
  11. 11. Example of Strategy Pattern Slide Use Strategy to plug-in a different implementation. CRT print() { print on console’s monitor } PaperPrinter print() { printOnLaserPrinter(); } Game void startGame() { … printer.printWinner(); … } Printer printer; Printer print()
  12. 12. Thanks