Your SlideShare is downloading. ×
Template Method Design Pattern
Upcoming SlideShare
Loading in...5

Thanks for flagging this SlideShare!

Oops! An error has occurred.


Saving this for later?

Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime - even offline.

Text the download link to your phone

Standard text messaging rates apply

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.

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

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

No notes for slide


  • 1. Template Method Pattern ~ Mother of all frameworks ~ Srikanth P Shreenivas [email_address]
  • 2. Game Console for playing Pool Slide public class Pool { aTypicalGamingSession() { startup(); retrieveLastSavedState(); displayPoolTable(); while (not exit) { acceptUserInput(); redrawTheTable(); } printWinner() saveUserScore; updateHighScores; } }
  • 3. Game Console – More games Slide
    • public class Game {
    • aTypicalGamingSession() {
    • startup();
    • retrieveLastSavedState();
    • if (game == pool);
    • displayPoolTable();
    • if (game == chess);
    • displayChessBoard();
    • while (not exit) {
    • acceptUserInput();
        • if (game == pool);
        • reCalculatePositionOfBalls();
        • if (game == chess);
        • reCalculatePositionsOfPawns();
    • }
    • printWinner()
    • saveUserScore;
    • updateHighScores;
    • }
    • }
  • 4. Game Console – What’s common? Slide
    • Every game has following sequence
      • User login
      • Retrieve last saved state.
      • Display the game.
      • React to user controls.
      • Save the game state.
      • Print winner
    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. Template Method Pattern Slide
    • Template method defines the steps of an algorithm, and allows subclasses to provide an implementation of one or more steps.
    • The template method is used for:
    • letting subclasses implement behavior that can vary
    • avoiding duplication in the code: you look for the general code in the algorithm, and implement the variants in the subclasses
    • controlling at what point(s) sub-classing is allowed.
    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. Inversion of control
    • Game class calls the method of sub-classes, thus, telling the sub-classes – “Don’t call me, I will call you”
    • Template method enforces “Open Closed Principle” – A class should be open for extension, but closed for modification”
    Slide Hollywood Principle
    • Inversion of Control
    • A key differentiator between frameworks and libraries
    • Framework invokes your code.
    • You invoke library’s code.
  • 7. Servlets – A case study for IoC
    • Life Cycle
      • init()
      • service()
      • destroy()
    • service() method is an abstract method in “GenericServlet” class.
    • HttpServlet is a sub-class of “GenericServlet”.
    • HttpServlet implements “service()” method.
    • Based on HTTP request type, HttpServlet invokes
      • doGet, doPost, doHead, doPut, doDelete(), doOptions(), doTrace().
    • HttpServlet’s service method defines a template for handling HTTP requests, it calls the right methods at right time.
    • Developers extend HttpServlet and write meaninful implementation of doGet, doPost, etc.
  • 8. Servlets – IoC and Template Method Pattern
    • We don’t control when our code is invoked.
    • Servlet container invokes our servlet’s code.
    • HttpServlet defines a template method , service(), which takes care of general purpose handling of HTTP requests by calling doGet, doPost…
    • We can extend HttpServlet by overriding the steps of the algorithm, doGet and doPost methods, to provide meaningful results.
    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. “ Mother of all frameworks”….How?
    • All frameworks implement some kind of “Inversion of Control”.
      • Examples: Servets, EJBs, Web Service Frameworks, Spring
    • Frameworks, which depend on application to extend it by sub-classing some of its classes, uses template method pattern.
      • Servlet’s doGet and doPost methods
    • 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.
      • MDB’s onMessage method
  • 10. Ways of Extending Classes (and Frameworks)
    • Inheritance
      • Use template method design pattern when you need to extend using inheritance
    • Composition
      • Use Strategy design pattern when you want to extend using composition
  • 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. Thanks