SlideShare a Scribd company logo
Template Method
Design Pattern
Presented by- Ridwan Hossain Talukder [23]
Asif Mahmud [31]
Sanad Saha [17]
1
Outline
• Introduction to Template Pattern.
• Why is it needed?
• A real life scenario.
• How the pattern works.
• Why is it different from other similar design patterns?
2
What is template pattern?
• The Template Method Pattern defines the skeleton of
an algorithm in a method deferring some steps to subclasses.
• The Template Method Pattern lets subclasses redefine
certain steps of an algorithm.
• But it doesn’t allow the subclasses to change the algorithm’s
structure.
3
Generalized Class Diagram
4
AbstractClass
templateMethod()
primitiveOperation1()
primitiveOperation2()
ConcreteClass
primitiveOperation1()
primitiveOperation2()
primitiveOperation1()
primitiveOperation2()
1. The abstract class
contains the template
method
2. And abstract versions of
the operations used in
the template method
The template method
makes use of the
primitiveOperations to
implement an algorithm
There may be many
concreteClasses, each
implementing the full
set of operations
required by the
template method
ConcreteMethods& Hooked methods
• It might be a case that a primitiveOperation is similar
for all concreteClasses, then it can be declared as a final
method inside the abstractClass.
• Another case might be that a primitiveOperation is not
needed in some concreteClasses, then that method can
be written inside those concreteClasses with a empty
body which are called Hooked Methods
5
Real Life Scenario
• A Software which includes games in which players play
against the others, but only one is playing at a given
time.
6
CHESS
MONOPOLY
The Similarities & The Dissimilarities
Similarities
• All these games have more than one player
• Only a player can play/ make moves at a single time
• Every game has an end
Dissimilarities
• Each game has its own rules, regulations and method of play
• Each game has a different way to choose the winner
7
One Way to do it
public class Game {
public String game;
public Game(String game) {
this.game = game;
}
protected int playersCount;
void initializeGame() {
if(game.equals(“Chess”)) {
// Initialize players
// Put the pieces on the board
}
else if(game.equals(“Monopoly”)) {
// Initialize players
// Initialize money
}
}
void makePlay(int player) { //Similar }
8
One Way to do it
boolean endOfGame(game) { //Similar }
void printWinner(game) { //Similar }
public void playOneGame(int playersCount) {
this.playersCount = playersCount;
initializeGame();
int j = 0;
while (!endOfGame()) {
makePlay(j);
j = (j + 1) % playersCount;
}
printWinner();
}
}
9
What is the problem?
• Every time a new game needs to be added, code have to
be modified.
• It violates a basic OOP rule which is -
Open for extension, closed for modification
10
Solution
11
Template
Method Design
Pattern!!!
Class Diagram
12
game
<<Template method>>
playOneGame()
<<Abstract Methods>>
initializeGame()
makePlay()
endOfGame()
<<Concrete Methods>>
printWinner()
chess
initializeGame()
makePlay()
endOfGame()
initializeGame()
makePlay()
endOfGame()
printWinner()
Monopoly
initializeGame()
makePlay()
endOfGame()
Implementation
abstract class Game {
protected int playersCount;
abstract void initializeGame();
abstract void makePlay(int player);
abstract boolean endOfGame();
/* A template method: */
public final void playOneGame(int playersCount) {
this.playersCount = playersCount;
initializeGame();
int j = 0;
while (!endOfGame()) {
makePlay(j);
j = (j + 1) % playersCount;
}
printWinner();
}
/* Concrete Methods: */
void printWinner() {
// Displays who won
}
}
13
Implementation
class Monopoly extends Game {
/* Concrete implementation of abstract methods For MONOPOLY GAME */
void initializeGame() {
// Initialize players
// Initialize money
}
void makePlay(int player) {
// Process one turn of player
}
boolean endOfGame() {
// Return true if game is over
// according to Monopoly rules
}
/* Specific declarations for the Monopoly game. */
// ...
}
14
Implementation
class Chess extends Game {
/* Concrete implementation of abstract methods For CHESS GAME */
void initializeGame() {
// Initialize players
// Put the pieces on the board
}
void makePlay(int player) {
// Process a turn for the player
}
boolean endOfGame() {
// Return true if in Checkmate or
// Stalemate has been reached
}
/* Specific declarations for the chess game. */
// ...
}
15
Applicability
• To implement the invariant parts of an algorithm once and leave it
up to subclasses to implement the behavior that can vary.
• When refactoring is performed and common behavior is identified
among classes. A abstract base class containing all the common
code (in the template method) should be created to avoid code
duplication and redundancy.
16
Another Powerful tool: The Hook
• Hook is a method that is declared in the abstract class
• “Hook” lets us to reconfigure our Template
• Hook gives us the choice if we want to override a method or not.
17
Using Hook in Template Pattern
18
abstract class AbstractClass {
final void templateMethod() {
primitiveOperation1();
primitiveOperation2();
concreteOperation();
if(HOOK_CustomerWantsOperation3()) {
primitiveOperation3();
}
}
abstract void primitiveOperation1();
abstract void primitiveOperation2();
abstract void primitiveOperation3();
final void concreteOperation() { }
boolean HOOK_CustomerWantsOperation3() {
if(condition satisfied) return true;
return false;
}
}
Difference with Strategy Pattern
• Strategy pattern means choosing an algorithm whereas Template
pattern means using an algorithm as a template to do similar but
not the same jobs.
• The Strategy pattern allows an algorithm to be chosen at runtime
by containment whereas with the Template method pattern this
happens at compile-time by subclassing the template.
• The difference consists in the fact that Strategy uses delegation
while the Template Methods uses the inheritance.
19
THANK YOU!
20
Ad

More Related Content

What's hot (20)

Prototype pattern
Prototype patternPrototype pattern
Prototype pattern
Shakil Ahmed
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
Satheesh Sukumaran
 
Mediator pattern
Mediator patternMediator pattern
Mediator pattern
Shakil Ahmed
 
Design patterns ppt
Design patterns pptDesign patterns ppt
Design patterns ppt
Aman Jain
 
Let us understand design pattern
Let us understand design patternLet us understand design pattern
Let us understand design pattern
Mindfire Solutions
 
The Singleton Pattern Presentation
The Singleton Pattern PresentationThe Singleton Pattern Presentation
The Singleton Pattern Presentation
JAINIK PATEL
 
Design Pattern For C# Part 1
Design Pattern For C# Part 1Design Pattern For C# Part 1
Design Pattern For C# Part 1
Shahzad
 
Design pattern-presentation
Design pattern-presentationDesign pattern-presentation
Design pattern-presentation
Rana Muhammad Asif
 
Factory Method Pattern
Factory Method PatternFactory Method Pattern
Factory Method Pattern
Anjan Kumar Bollam
 
Applets in java
Applets in javaApplets in java
Applets in java
Wani Zahoor
 
Tomcat server
 Tomcat server Tomcat server
Tomcat server
Utkarsh Agarwal
 
Iterator Design Pattern
Iterator Design PatternIterator Design Pattern
Iterator Design Pattern
Varun Arora
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Raghu nath
 
Singleton design pattern
Singleton design patternSingleton design pattern
Singleton design pattern
11prasoon
 
Observer Software Design Pattern
Observer Software Design Pattern Observer Software Design Pattern
Observer Software Design Pattern
Nirthika Rajendran
 
Design Patterns - Abstract Factory Pattern
Design Patterns - Abstract Factory PatternDesign Patterns - Abstract Factory Pattern
Design Patterns - Abstract Factory Pattern
Mudasir Qazi
 
Builder pattern
Builder patternBuilder pattern
Builder pattern
Shakil Ahmed
 
Java Course 11: Design Patterns
Java Course 11: Design PatternsJava Course 11: Design Patterns
Java Course 11: Design Patterns
Anton Keks
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
BHUVIJAYAVELU
 
Boxing & unboxing
Boxing & unboxingBoxing & unboxing
Boxing & unboxing
Larry Nung
 
Design patterns ppt
Design patterns pptDesign patterns ppt
Design patterns ppt
Aman Jain
 
Let us understand design pattern
Let us understand design patternLet us understand design pattern
Let us understand design pattern
Mindfire Solutions
 
The Singleton Pattern Presentation
The Singleton Pattern PresentationThe Singleton Pattern Presentation
The Singleton Pattern Presentation
JAINIK PATEL
 
Design Pattern For C# Part 1
Design Pattern For C# Part 1Design Pattern For C# Part 1
Design Pattern For C# Part 1
Shahzad
 
Iterator Design Pattern
Iterator Design PatternIterator Design Pattern
Iterator Design Pattern
Varun Arora
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Raghu nath
 
Singleton design pattern
Singleton design patternSingleton design pattern
Singleton design pattern
11prasoon
 
Observer Software Design Pattern
Observer Software Design Pattern Observer Software Design Pattern
Observer Software Design Pattern
Nirthika Rajendran
 
Design Patterns - Abstract Factory Pattern
Design Patterns - Abstract Factory PatternDesign Patterns - Abstract Factory Pattern
Design Patterns - Abstract Factory Pattern
Mudasir Qazi
 
Java Course 11: Design Patterns
Java Course 11: Design PatternsJava Course 11: Design Patterns
Java Course 11: Design Patterns
Anton Keks
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
BHUVIJAYAVELU
 
Boxing & unboxing
Boxing & unboxingBoxing & unboxing
Boxing & unboxing
Larry Nung
 

Viewers also liked (11)

Template Method Design Pattern
Template Method Design PatternTemplate Method Design Pattern
Template Method Design Pattern
Srikanth Shreenivas
 
Template method pattern example
Template method pattern exampleTemplate method pattern example
Template method pattern example
Guo Albert
 
Apply Template Method Pattern in Report Implementation
Apply Template Method Pattern in Report ImplementationApply Template Method Pattern in Report Implementation
Apply Template Method Pattern in Report Implementation
Guo Albert
 
The benefits of erp products
The benefits of erp productsThe benefits of erp products
The benefits of erp products
Ecreations india
 
Template Method Pattern
Template Method PatternTemplate Method Pattern
Template Method Pattern
monisiqbal
 
Adapter Design Pattern
Adapter Design PatternAdapter Design Pattern
Adapter Design Pattern
melbournepatterns
 
Adapter Pattern Abhijit Hiremagalur 200603
Adapter Pattern Abhijit Hiremagalur 200603Adapter Pattern Abhijit Hiremagalur 200603
Adapter Pattern Abhijit Hiremagalur 200603
melbournepatterns
 
Adapter Design Pattern
Adapter Design PatternAdapter Design Pattern
Adapter Design Pattern
Shahriar Iqbal Chowdhury
 
Adapter Design Pattern
Adapter Design PatternAdapter Design Pattern
Adapter Design Pattern
guy_davis
 
Adapter Design Pattern
Adapter Design PatternAdapter Design Pattern
Adapter Design Pattern
Adeel Riaz
 
Software design patterns ppt
Software design patterns pptSoftware design patterns ppt
Software design patterns ppt
mkruthika
 
Template method pattern example
Template method pattern exampleTemplate method pattern example
Template method pattern example
Guo Albert
 
Apply Template Method Pattern in Report Implementation
Apply Template Method Pattern in Report ImplementationApply Template Method Pattern in Report Implementation
Apply Template Method Pattern in Report Implementation
Guo Albert
 
The benefits of erp products
The benefits of erp productsThe benefits of erp products
The benefits of erp products
Ecreations india
 
Template Method Pattern
Template Method PatternTemplate Method Pattern
Template Method Pattern
monisiqbal
 
Adapter Pattern Abhijit Hiremagalur 200603
Adapter Pattern Abhijit Hiremagalur 200603Adapter Pattern Abhijit Hiremagalur 200603
Adapter Pattern Abhijit Hiremagalur 200603
melbournepatterns
 
Adapter Design Pattern
Adapter Design PatternAdapter Design Pattern
Adapter Design Pattern
guy_davis
 
Adapter Design Pattern
Adapter Design PatternAdapter Design Pattern
Adapter Design Pattern
Adeel Riaz
 
Software design patterns ppt
Software design patterns pptSoftware design patterns ppt
Software design patterns ppt
mkruthika
 
Ad

Similar to Presentation on Template Method Design Pattern (20)

Lesson12 other behavioural patterns
Lesson12 other behavioural patternsLesson12 other behavioural patterns
Lesson12 other behavioural patterns
OktJona
 
L10 Using Frameworks
L10 Using FrameworksL10 Using Frameworks
L10 Using Frameworks
Ólafur Andri Ragnarsson
 
Hi there I am having difficulty in finalizing my Tetris game , below.pdf
Hi there I am having difficulty in finalizing my Tetris game , below.pdfHi there I am having difficulty in finalizing my Tetris game , below.pdf
Hi there I am having difficulty in finalizing my Tetris game , below.pdf
fonecomp
 
L08 Using Frameworks
L08 Using FrameworksL08 Using Frameworks
L08 Using Frameworks
Ólafur Andri Ragnarsson
 
Parameters
ParametersParameters
Parameters
James Brotsos
 
Enterprise Tic-Tac-Toe
Enterprise Tic-Tac-ToeEnterprise Tic-Tac-Toe
Enterprise Tic-Tac-Toe
Scott Wlaschin
 
Jdk 7 4-forkjoin
Jdk 7 4-forkjoinJdk 7 4-forkjoin
Jdk 7 4-forkjoin
knight1128
 
Intake 38 12
Intake 38 12Intake 38 12
Intake 38 12
Mahmoud Ouf
 
OPERATNG SYSTEM MODULE-2 PRESENTATION OS
OPERATNG SYSTEM MODULE-2 PRESENTATION OSOPERATNG SYSTEM MODULE-2 PRESENTATION OS
OPERATNG SYSTEM MODULE-2 PRESENTATION OS
tharaniraiml
 
40d5984d819aaa72e55aa10376b73bde_MIT6_087IAP10_lec12.pdf
40d5984d819aaa72e55aa10376b73bde_MIT6_087IAP10_lec12.pdf40d5984d819aaa72e55aa10376b73bde_MIT6_087IAP10_lec12.pdf
40d5984d819aaa72e55aa10376b73bde_MIT6_087IAP10_lec12.pdf
SagarYadav642223
 
lecture56functionsggggggggggggggggggg.ppt
lecture56functionsggggggggggggggggggg.pptlecture56functionsggggggggggggggggggg.ppt
lecture56functionsggggggggggggggggggg.ppt
abuharb789
 
lecture56.ppt
lecture56.pptlecture56.ppt
lecture56.ppt
AqeelAbbas94
 
A Proposal to Orchestrate Test Cases
A Proposal to Orchestrate Test CasesA Proposal to Orchestrate Test Cases
A Proposal to Orchestrate Test Cases
Boni García
 
Implmenting an Experiment in oTree
Implmenting an Experiment in oTreeImplmenting an Experiment in oTree
Implmenting an Experiment in oTree
eurosigdoc acm
 
Mastermind design walkthrough
Mastermind design walkthroughMastermind design walkthrough
Mastermind design walkthrough
Amir Shadaab Mohammed
 
Java Multithreading - how to create threads
Java Multithreading - how to create threadsJava Multithreading - how to create threads
Java Multithreading - how to create threads
ManishKumar475693
 
Threads
ThreadsThreads
Threads
RanjithaM32
 
Working with Layout Managers. Notes 1. In part 2, note that the Gam.pdf
Working with Layout Managers. Notes 1. In part 2, note that the Gam.pdfWorking with Layout Managers. Notes 1. In part 2, note that the Gam.pdf
Working with Layout Managers. Notes 1. In part 2, note that the Gam.pdf
udit652068
 
You will write a multi-interface version of the well-known concentra.pdf
You will write a multi-interface version of the well-known concentra.pdfYou will write a multi-interface version of the well-known concentra.pdf
You will write a multi-interface version of the well-known concentra.pdf
FashionColZone
 
GeeCON 2012 Bad Tests, Good Tests
GeeCON 2012 Bad Tests, Good TestsGeeCON 2012 Bad Tests, Good Tests
GeeCON 2012 Bad Tests, Good Tests
Tomek Kaczanowski
 
Lesson12 other behavioural patterns
Lesson12 other behavioural patternsLesson12 other behavioural patterns
Lesson12 other behavioural patterns
OktJona
 
Hi there I am having difficulty in finalizing my Tetris game , below.pdf
Hi there I am having difficulty in finalizing my Tetris game , below.pdfHi there I am having difficulty in finalizing my Tetris game , below.pdf
Hi there I am having difficulty in finalizing my Tetris game , below.pdf
fonecomp
 
Enterprise Tic-Tac-Toe
Enterprise Tic-Tac-ToeEnterprise Tic-Tac-Toe
Enterprise Tic-Tac-Toe
Scott Wlaschin
 
Jdk 7 4-forkjoin
Jdk 7 4-forkjoinJdk 7 4-forkjoin
Jdk 7 4-forkjoin
knight1128
 
OPERATNG SYSTEM MODULE-2 PRESENTATION OS
OPERATNG SYSTEM MODULE-2 PRESENTATION OSOPERATNG SYSTEM MODULE-2 PRESENTATION OS
OPERATNG SYSTEM MODULE-2 PRESENTATION OS
tharaniraiml
 
40d5984d819aaa72e55aa10376b73bde_MIT6_087IAP10_lec12.pdf
40d5984d819aaa72e55aa10376b73bde_MIT6_087IAP10_lec12.pdf40d5984d819aaa72e55aa10376b73bde_MIT6_087IAP10_lec12.pdf
40d5984d819aaa72e55aa10376b73bde_MIT6_087IAP10_lec12.pdf
SagarYadav642223
 
lecture56functionsggggggggggggggggggg.ppt
lecture56functionsggggggggggggggggggg.pptlecture56functionsggggggggggggggggggg.ppt
lecture56functionsggggggggggggggggggg.ppt
abuharb789
 
A Proposal to Orchestrate Test Cases
A Proposal to Orchestrate Test CasesA Proposal to Orchestrate Test Cases
A Proposal to Orchestrate Test Cases
Boni García
 
Implmenting an Experiment in oTree
Implmenting an Experiment in oTreeImplmenting an Experiment in oTree
Implmenting an Experiment in oTree
eurosigdoc acm
 
Java Multithreading - how to create threads
Java Multithreading - how to create threadsJava Multithreading - how to create threads
Java Multithreading - how to create threads
ManishKumar475693
 
Working with Layout Managers. Notes 1. In part 2, note that the Gam.pdf
Working with Layout Managers. Notes 1. In part 2, note that the Gam.pdfWorking with Layout Managers. Notes 1. In part 2, note that the Gam.pdf
Working with Layout Managers. Notes 1. In part 2, note that the Gam.pdf
udit652068
 
You will write a multi-interface version of the well-known concentra.pdf
You will write a multi-interface version of the well-known concentra.pdfYou will write a multi-interface version of the well-known concentra.pdf
You will write a multi-interface version of the well-known concentra.pdf
FashionColZone
 
GeeCON 2012 Bad Tests, Good Tests
GeeCON 2012 Bad Tests, Good TestsGeeCON 2012 Bad Tests, Good Tests
GeeCON 2012 Bad Tests, Good Tests
Tomek Kaczanowski
 
Ad

Recently uploaded (20)

Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam SuccessUltimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Mark Soia
 
LDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini UpdatesLDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini Updates
LDM Mia eStudios
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
larencebapu132
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
Social Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy StudentsSocial Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy Students
DrNidhiAgarwal
 
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
Operations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdfOperations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdf
Arab Academy for Science, Technology and Maritime Transport
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam SuccessUltimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Mark Soia
 
LDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini UpdatesLDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini Updates
LDM Mia eStudios
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
larencebapu132
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
Social Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy StudentsSocial Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy Students
DrNidhiAgarwal
 
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 

Presentation on Template Method Design Pattern

  • 1. Template Method Design Pattern Presented by- Ridwan Hossain Talukder [23] Asif Mahmud [31] Sanad Saha [17] 1
  • 2. Outline • Introduction to Template Pattern. • Why is it needed? • A real life scenario. • How the pattern works. • Why is it different from other similar design patterns? 2
  • 3. What is template pattern? • The Template Method Pattern defines the skeleton of an algorithm in a method deferring some steps to subclasses. • The Template Method Pattern lets subclasses redefine certain steps of an algorithm. • But it doesn’t allow the subclasses to change the algorithm’s structure. 3
  • 4. Generalized Class Diagram 4 AbstractClass templateMethod() primitiveOperation1() primitiveOperation2() ConcreteClass primitiveOperation1() primitiveOperation2() primitiveOperation1() primitiveOperation2() 1. The abstract class contains the template method 2. And abstract versions of the operations used in the template method The template method makes use of the primitiveOperations to implement an algorithm There may be many concreteClasses, each implementing the full set of operations required by the template method
  • 5. ConcreteMethods& Hooked methods • It might be a case that a primitiveOperation is similar for all concreteClasses, then it can be declared as a final method inside the abstractClass. • Another case might be that a primitiveOperation is not needed in some concreteClasses, then that method can be written inside those concreteClasses with a empty body which are called Hooked Methods 5
  • 6. Real Life Scenario • A Software which includes games in which players play against the others, but only one is playing at a given time. 6 CHESS MONOPOLY
  • 7. The Similarities & The Dissimilarities Similarities • All these games have more than one player • Only a player can play/ make moves at a single time • Every game has an end Dissimilarities • Each game has its own rules, regulations and method of play • Each game has a different way to choose the winner 7
  • 8. One Way to do it public class Game { public String game; public Game(String game) { this.game = game; } protected int playersCount; void initializeGame() { if(game.equals(“Chess”)) { // Initialize players // Put the pieces on the board } else if(game.equals(“Monopoly”)) { // Initialize players // Initialize money } } void makePlay(int player) { //Similar } 8
  • 9. One Way to do it boolean endOfGame(game) { //Similar } void printWinner(game) { //Similar } public void playOneGame(int playersCount) { this.playersCount = playersCount; initializeGame(); int j = 0; while (!endOfGame()) { makePlay(j); j = (j + 1) % playersCount; } printWinner(); } } 9
  • 10. What is the problem? • Every time a new game needs to be added, code have to be modified. • It violates a basic OOP rule which is - Open for extension, closed for modification 10
  • 12. Class Diagram 12 game <<Template method>> playOneGame() <<Abstract Methods>> initializeGame() makePlay() endOfGame() <<Concrete Methods>> printWinner() chess initializeGame() makePlay() endOfGame() initializeGame() makePlay() endOfGame() printWinner() Monopoly initializeGame() makePlay() endOfGame()
  • 13. Implementation abstract class Game { protected int playersCount; abstract void initializeGame(); abstract void makePlay(int player); abstract boolean endOfGame(); /* A template method: */ public final void playOneGame(int playersCount) { this.playersCount = playersCount; initializeGame(); int j = 0; while (!endOfGame()) { makePlay(j); j = (j + 1) % playersCount; } printWinner(); } /* Concrete Methods: */ void printWinner() { // Displays who won } } 13
  • 14. Implementation class Monopoly extends Game { /* Concrete implementation of abstract methods For MONOPOLY GAME */ void initializeGame() { // Initialize players // Initialize money } void makePlay(int player) { // Process one turn of player } boolean endOfGame() { // Return true if game is over // according to Monopoly rules } /* Specific declarations for the Monopoly game. */ // ... } 14
  • 15. Implementation class Chess extends Game { /* Concrete implementation of abstract methods For CHESS GAME */ void initializeGame() { // Initialize players // Put the pieces on the board } void makePlay(int player) { // Process a turn for the player } boolean endOfGame() { // Return true if in Checkmate or // Stalemate has been reached } /* Specific declarations for the chess game. */ // ... } 15
  • 16. Applicability • To implement the invariant parts of an algorithm once and leave it up to subclasses to implement the behavior that can vary. • When refactoring is performed and common behavior is identified among classes. A abstract base class containing all the common code (in the template method) should be created to avoid code duplication and redundancy. 16
  • 17. Another Powerful tool: The Hook • Hook is a method that is declared in the abstract class • “Hook” lets us to reconfigure our Template • Hook gives us the choice if we want to override a method or not. 17
  • 18. Using Hook in Template Pattern 18 abstract class AbstractClass { final void templateMethod() { primitiveOperation1(); primitiveOperation2(); concreteOperation(); if(HOOK_CustomerWantsOperation3()) { primitiveOperation3(); } } abstract void primitiveOperation1(); abstract void primitiveOperation2(); abstract void primitiveOperation3(); final void concreteOperation() { } boolean HOOK_CustomerWantsOperation3() { if(condition satisfied) return true; return false; } }
  • 19. Difference with Strategy Pattern • Strategy pattern means choosing an algorithm whereas Template pattern means using an algorithm as a template to do similar but not the same jobs. • The Strategy pattern allows an algorithm to be chosen at runtime by containment whereas with the Template method pattern this happens at compile-time by subclassing the template. • The difference consists in the fact that Strategy uses delegation while the Template Methods uses the inheritance. 19