Template Method Design Pattern

Loading...

Flash Player 9 (or above) is needed to view presentations.
We have detected that you do not have it on your computer. To install it, go here.

0 comments

Post a comment

    Post a comment
    Embed Video
    Edit your comment Cancel

    2 Favorites

    Template Method Design Pattern - Presentation Transcript

    1. Template Method Pattern ~ Mother of all frameworks ~ Srikanth P Shreenivas [email_address] http://www.srikanthps.com
    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.
      Slide
    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
      Slide
    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
      Slide
    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

    + Srikanth ShreenivasSrikanth Shreenivas, 9 months ago

    custom

    1143 views, 2 favs, 0 embeds more stats

    Template method design pattern is quite useful for more

    More info about this document

    © All Rights Reserved

    Go to text version

    • Total Views 1143
      • 1143 on SlideShare
      • 0 from embeds
    • Comments 0
    • Favorites 2
    • Downloads 65
    Most viewed embeds

    more

    All embeds

    less

    Flagged as inappropriate Flag as inappropriate
    Flag as inappropriate

    Select your reason for flagging this presentation as inappropriate. If needed, use the feedback form to let us know more details.

    Cancel
    File a copyright complaint
    Having problems? Go to our helpdesk?

    Categories