Template Method Design Pattern
Upcoming SlideShare
Loading in...5
×
 

Template Method Design Pattern

on

  • 5,159 views

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.

Statistics

Views

Total Views
5,159
Views on SlideShare
5,113
Embed Views
46

Actions

Likes
2
Downloads
131
Comments
0

3 Embeds 46

http://www.slideshare.net 26
http://www.linkedin.com 12
https://www.linkedin.com 8

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Template Method Design Pattern Template Method Design Pattern Presentation Transcript

  • Template Method Pattern ~ Mother of all frameworks ~ Srikanth P Shreenivas [email_address] http://www.srikanthps.com
  • Game Console for playing Pool Slide public class Pool { aTypicalGamingSession() { startup(); retrieveLastSavedState(); displayPoolTable(); while (not exit) { acceptUserInput(); redrawTheTable(); } printWinner() saveUserScore; updateHighScores; } }
  • 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;
    • }
    • }
  • 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(); }
  • 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() { }
  • 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.
  • 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
  • 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.
  • “ 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
  • 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
  • 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()
  • Thanks