template method design pattern

12
Template Method Pattern ~ Mother of all frameworks ~ Srikanth P Shreenivas [email protected] http://www.srikanthps.com

Upload: srikanth-shreenivas

Post on 27-May-2015

3.168 views

Category:

Technology


2 download

DESCRIPTION

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

TRANSCRIPT

Template Method Pattern~ Mother of all frameworks ~

Srikanth P [email protected]

http://www.srikanthps.com

Slide 2

Game Console for playing Poolpublic class Pool { aTypicalGamingSession() {

startup();

retrieveLastSavedState();

displayPoolTable();

while (not exit) { acceptUserInput(); redrawTheTable();}

printWinner()

saveUserScore;

updateHighScores; }}

Slide 3

Game Console – More games

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;

}}

Slide 4

Game Console – What’s common?

•Every game has following sequence• User login• Retrieve last saved state.• Display the game.• React to user controls.• Save the game state.• Print winner

GameGamestartGame() { retrieveLastSavedState(); displayGame(); while (not exit) { reactToUserControl(); } saveGame(); printWinner();}Abstract displayGame();Abstract reactToUserControl();

startGame() { retrieveLastSavedState(); displayGame(); while (not exit) { reactToUserControl(); } saveGame(); printWinner();}Abstract displayGame();Abstract reactToUserControl();

ChessChessdisplayGame() { displayChessBoard();}

reactToUserControl() { moveThePiece();}

displayGame() { displayChessBoard();}

reactToUserControl() { moveThePiece();}

PoolPooldisplayGame() { displayPoolTable();}

reactToUserControl() { strikeWithCueBall();}

displayGame() { displayPoolTable();}

reactToUserControl() { strikeWithCueBall();}

Delegate game specific behavior to derived classes, while controlling the main game behavior in base class.Delegate game specific behavior to derived classes, while controlling the main game behavior in base class.

Common Behavior

Game-specific Behavior

Slide 5

Template Method PatternTemplate 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.

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 2step1() { }step3OptionalStep() { //diff. implementation }

Algorithm() { step1(); step2MustAlwaysDoThis(); step3OptionalStep(); step4finalStep();}

Abstract step1();

Final step2MustAlwaysDoThis() {}

step3OptionalStep() { //Default code}

Final step4FinalStep() {}

Base ClassConcreteClass 1

step1() { }

Slide 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”

Hollywood PrincipleHollywood Principle

Inversion of Control• A key differentiator between frameworks and libraries• Framework invokes your code.• You invoke library’s code.

Inversion of Control• A key differentiator between frameworks and libraries• Framework invokes your code.• You invoke library’s code.

Slide 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.

Servlet Container’s Hollywood Principle:

Don’t call me, I will call you (servlet) !!! (whenever I hear from a browser)

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.

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.

Slide 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

CRTCRT

print() { print on console’s monitor}

print() { print on console’s monitor}

PaperPrinterPaperPrinter

print() { printOnLaserPrinter();}

print() { printOnLaserPrinter();}

GameGame

void startGame() { … printer.printWinner(); …}

void startGame() { … printer.printWinner(); …}

Printer printer;Printer printer;PrinterPrinter

print()print()

Use Strategy to plug-in a different implementation.

Thanks