SlideShare a Scribd company logo
Design Patterns
Template Method
Template Method
Template method defines the skeleton of an
algorithm in an operation, deferring some steps
to subclasses. Template Method lets
subclasses redefine certain steps of an
algorithm without changing the algorithm’s
structure
Abstract Class
Abstract methods that defines the basic steps
of the algorithm with
‘main’ method is public and defines the
algorithm structure (skeleton)
deferring actual implementation to subclasses
Components
Abstract methods (must override)
Non-abstract methods (can’t override)
Hook methods (may override - abstract)
Need a convention to separate Abstract from Hook methods (for example, DoMethod() may signify
that this is an abstract method that must be implemented)
Subclasses
Implements the abstract methods into real
actions
Subclasses implementation may differ.
Subclasses can override/redefine certain steps
of an algorithm but algorithm’s structure
remains intact
Strength
Changing behaviours - subclasses implements specific
behaviour
Avoids code duplication - overall work flow is implemented
once
Control - specifies what can and can’t change. Only
specific things are allowed to change
Code Sample
abstract class Generalization {
// 1. Standardize the skeleton of an algorithm in a "template" method
public void findSolution() {
stepOne();
stepTwo();
stepThr();
stepFor();
}
// 2. Common implementations of individual steps are defined in base class
protected void stepOne() { System.out.println( "Generalization.stepOne" ); }
// 3. Steps requiring peculiar impls are ";placeholders" in the base class
abstract protected void stepTwo();
abstract protected void stepThr();
protected void stepFor() { System.out.println( "Generalization.stepFor" ); }
}
Code Sample (contd)
abstract class Specialization extends Generalization {
// 4. Derived classes can override placeholder methods
// 1. Standardize the skeleton of an algorithm in a "template" method
protected void stepThr() {
step3_1();
step3_2();
step3_3();
}
// 2. Common implementations of individual steps are defined in base class
protected void step3_1() { System.out.println( "Specialization.step3_1" ); }
// 3. Steps requiring peculiar impls are "placeholders" in the base class
abstract protected void step3_2();
protected void step3_3() { System.out.println( "Specialization.step3_3" ); }
}
Code Sample (contd)
class Realization extends Specialization {
// 4. Derived classes can override placeholder methods
protected void stepTwo() { System.out.println( "Realization .stepTwo" ); }
protected void step3_2() { System.out.println( "Realization .step3_2" ); }
// 5. Derived classes can override implemented methods
// 6. Derived classes can override and "call back to" base class methods
protected void stepFor() {
System.out.println( "Realization .stepFor" );
super.stepFor();
} }
class TemplateMethodDemo {
public static void main( String[] args ) {
Generalization algorithm = new Realization();
algorithm.findSolution();
} }
Output (code_sample)
Generalization.stepOne
Realization.stepTwo
Specialization.step3_1
Realization.step3_2
Specialization.step3_3
Realization.stepFor
Generalization.stepFor
Real world Implementation
abstract class Game {
protected int playersCount;
abstract void initializeGame();
abstract void makePlay(int player);
abstract boolean endOfGame();
abstract void printWinner();
/* 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();
}
}
Real world Implementation
//Now we can extend this class in order
//to implement actual games:
class Monopoly extends Game {
/* Implementation of necessary concrete methods */
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
}
void printWinner() {
// Display who won
}
/* Specific declarations for the Monopoly game. */
}
Real World Implementation
class Chess extends Game {
/* Implementation of necessary concrete methods */
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
}
void printWinner() {
// Display the winning player
}
/* Specific declarations for the chess game. */
// ...
}
..and the one-liner
The Template pattern does compile-time algorithm selection by subclassing.

More Related Content

What's hot

Control structures in java
Control structures in javaControl structures in java
Control structures in java
VINOTH R
 
Spring aop
Spring aopSpring aop
Spring aop
UMA MAHESWARI
 
M C6java6
M C6java6M C6java6
M C6java6
mbruggen
 
Md04 flow control
Md04 flow controlMd04 flow control
Md04 flow control
Rakesh Madugula
 
Java conditional statements
Java conditional statementsJava conditional statements
Java conditional statements
Kuppusamy P
 
Control statements in java programmng
Control statements in java programmngControl statements in java programmng
Control statements in java programmng
Savitribai Phule Pune University
 
Java Decision Control
Java Decision ControlJava Decision Control
Java Decision Control
Jayfee Ramos
 
Java findamentals2
Java findamentals2Java findamentals2
Java findamentals2
Todor Kolev
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Kavitha713564
 
Control structures
Control structuresControl structures
Control structures
M Vishnuvardhan Reddy
 
Control structures i
Control structures i Control structures i
Control structures i
Ahmad Idrees
 
Control structures in Java
Control structures in JavaControl structures in Java
Control structures in Java
Ravi_Kant_Sahu
 
Method overloading
Method overloadingMethod overloading
How to test models using php unit testing framework?
How to test models using php unit testing framework?How to test models using php unit testing framework?
How to test models using php unit testing framework?
satejsahu
 
Interfaces
InterfacesInterfaces
Interfaces
RBIEBT,MOHALI
 
Control structures ii
Control structures ii Control structures ii
Control structures ii
Ahmad Idrees
 
Java loops for, while and do...while
Java loops   for, while and do...whileJava loops   for, while and do...while
Java loops for, while and do...while
Jayfee Ramos
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
kamal kotecha
 
Java adapter
Java adapterJava adapter
Java adapter
Arati Gadgil
 
Std 12 Computer Chapter 7 Java Basics (Part 2)
Std 12 Computer Chapter 7 Java Basics (Part 2)Std 12 Computer Chapter 7 Java Basics (Part 2)
Std 12 Computer Chapter 7 Java Basics (Part 2)
Nuzhat Memon
 

What's hot (20)

Control structures in java
Control structures in javaControl structures in java
Control structures in java
 
Spring aop
Spring aopSpring aop
Spring aop
 
M C6java6
M C6java6M C6java6
M C6java6
 
Md04 flow control
Md04 flow controlMd04 flow control
Md04 flow control
 
Java conditional statements
Java conditional statementsJava conditional statements
Java conditional statements
 
Control statements in java programmng
Control statements in java programmngControl statements in java programmng
Control statements in java programmng
 
Java Decision Control
Java Decision ControlJava Decision Control
Java Decision Control
 
Java findamentals2
Java findamentals2Java findamentals2
Java findamentals2
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Control structures
Control structuresControl structures
Control structures
 
Control structures i
Control structures i Control structures i
Control structures i
 
Control structures in Java
Control structures in JavaControl structures in Java
Control structures in Java
 
Method overloading
Method overloadingMethod overloading
Method overloading
 
How to test models using php unit testing framework?
How to test models using php unit testing framework?How to test models using php unit testing framework?
How to test models using php unit testing framework?
 
Interfaces
InterfacesInterfaces
Interfaces
 
Control structures ii
Control structures ii Control structures ii
Control structures ii
 
Java loops for, while and do...while
Java loops   for, while and do...whileJava loops   for, while and do...while
Java loops for, while and do...while
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Java adapter
Java adapterJava adapter
Java adapter
 
Std 12 Computer Chapter 7 Java Basics (Part 2)
Std 12 Computer Chapter 7 Java Basics (Part 2)Std 12 Computer Chapter 7 Java Basics (Part 2)
Std 12 Computer Chapter 7 Java Basics (Part 2)
 

Similar to Design patterns: template method

template method.pptx
template method.pptxtemplate method.pptx
template method.pptx
LightYagami329214
 
Chapter 8 Inheritance
Chapter 8 InheritanceChapter 8 Inheritance
Chapter 8 Inheritance
OUM SAOKOSAL
 
Abstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core JavaAbstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core Java
MOHIT AGARWAL
 
Java Reflection
Java ReflectionJava Reflection
Java Reflection
Hamid Ghorbani
 
Java Unit 2(part 3)
Java Unit 2(part 3)Java Unit 2(part 3)
Java Unit 2(part 3)
SURBHI SAROHA
 
Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in java
Ahsan Raja
 
Working with Methods in Java.pptx
Working with Methods in Java.pptxWorking with Methods in Java.pptx
Working with Methods in Java.pptx
maryansagsgao
 
polymorphismpresentation-160825122725.pdf
polymorphismpresentation-160825122725.pdfpolymorphismpresentation-160825122725.pdf
polymorphismpresentation-160825122725.pdf
BapanKar2
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
backdoor
 
Understanding Annotations in Java
Understanding Annotations in JavaUnderstanding Annotations in Java
Understanding Annotations in Java
Ecommerce Solution Provider SysIQ
 
Lecture5_Method_overloading_Final power point presentation
Lecture5_Method_overloading_Final power point presentationLecture5_Method_overloading_Final power point presentation
Lecture5_Method_overloading_Final power point presentation
bhargavi804095
 
Lecture4_Method_overloading power point presentaion
Lecture4_Method_overloading power point presentaionLecture4_Method_overloading power point presentaion
Lecture4_Method_overloading power point presentaion
bhargavi804095
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
RubaNagarajan
 
Computer programming 2 Lesson 15
Computer programming 2  Lesson 15Computer programming 2  Lesson 15
Computer programming 2 Lesson 15
MLG College of Learning, Inc
 
Lesson12 other behavioural patterns
Lesson12 other behavioural patternsLesson12 other behavioural patterns
Lesson12 other behavioural patterns
OktJona
 
TDD And Refactoring
TDD And RefactoringTDD And Refactoring
TDD And Refactoring
Naresh Jain
 
Chapter8
Chapter8Chapter8
java tutorial 4
 java tutorial 4 java tutorial 4
java tutorial 4
Tushar Desarda
 
L09 Frameworks
L09 FrameworksL09 Frameworks
L09 Frameworks
Ólafur Andri Ragnarsson
 
Unit 4 notes.pdf
Unit 4 notes.pdfUnit 4 notes.pdf
Unit 4 notes.pdf
Revathiparamanathan
 

Similar to Design patterns: template method (20)

template method.pptx
template method.pptxtemplate method.pptx
template method.pptx
 
Chapter 8 Inheritance
Chapter 8 InheritanceChapter 8 Inheritance
Chapter 8 Inheritance
 
Abstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core JavaAbstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core Java
 
Java Reflection
Java ReflectionJava Reflection
Java Reflection
 
Java Unit 2(part 3)
Java Unit 2(part 3)Java Unit 2(part 3)
Java Unit 2(part 3)
 
Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in java
 
Working with Methods in Java.pptx
Working with Methods in Java.pptxWorking with Methods in Java.pptx
Working with Methods in Java.pptx
 
polymorphismpresentation-160825122725.pdf
polymorphismpresentation-160825122725.pdfpolymorphismpresentation-160825122725.pdf
polymorphismpresentation-160825122725.pdf
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
 
Understanding Annotations in Java
Understanding Annotations in JavaUnderstanding Annotations in Java
Understanding Annotations in Java
 
Lecture5_Method_overloading_Final power point presentation
Lecture5_Method_overloading_Final power point presentationLecture5_Method_overloading_Final power point presentation
Lecture5_Method_overloading_Final power point presentation
 
Lecture4_Method_overloading power point presentaion
Lecture4_Method_overloading power point presentaionLecture4_Method_overloading power point presentaion
Lecture4_Method_overloading power point presentaion
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
 
Computer programming 2 Lesson 15
Computer programming 2  Lesson 15Computer programming 2  Lesson 15
Computer programming 2 Lesson 15
 
Lesson12 other behavioural patterns
Lesson12 other behavioural patternsLesson12 other behavioural patterns
Lesson12 other behavioural patterns
 
TDD And Refactoring
TDD And RefactoringTDD And Refactoring
TDD And Refactoring
 
Chapter8
Chapter8Chapter8
Chapter8
 
java tutorial 4
 java tutorial 4 java tutorial 4
java tutorial 4
 
L09 Frameworks
L09 FrameworksL09 Frameworks
L09 Frameworks
 
Unit 4 notes.pdf
Unit 4 notes.pdfUnit 4 notes.pdf
Unit 4 notes.pdf
 

More from Babatunde Ishola

Achieving Highly Effective Personalized Learning through Learning Objects
Achieving Highly Effective Personalized Learning through Learning ObjectsAchieving Highly Effective Personalized Learning through Learning Objects
Achieving Highly Effective Personalized Learning through Learning Objects
Babatunde Ishola
 
Report on the Strength of materials i lab
Report on the Strength of materials i labReport on the Strength of materials i lab
Report on the Strength of materials i lab
Babatunde Ishola
 
ISHOLA Babatunde Isaac (CV)
ISHOLA Babatunde Isaac (CV)ISHOLA Babatunde Isaac (CV)
ISHOLA Babatunde Isaac (CV)
Babatunde Ishola
 
REMOTE REALISTIC INTERFACE EXPERIMENTATION USING THE EMONA DATEX BOARD
REMOTE REALISTIC INTERFACE EXPERIMENTATION USING THE EMONA DATEX BOARDREMOTE REALISTIC INTERFACE EXPERIMENTATION USING THE EMONA DATEX BOARD
REMOTE REALISTIC INTERFACE EXPERIMENTATION USING THE EMONA DATEX BOARD
Babatunde Ishola
 
AN IMPROVED OPERATIONAL AMPLIFIER ILAB WITH A MORE REALISTIC LOOKING INTERFACE
AN IMPROVED OPERATIONAL AMPLIFIER ILAB WITH A MORE REALISTIC LOOKING INTERFACEAN IMPROVED OPERATIONAL AMPLIFIER ILAB WITH A MORE REALISTIC LOOKING INTERFACE
AN IMPROVED OPERATIONAL AMPLIFIER ILAB WITH A MORE REALISTIC LOOKING INTERFACE
Babatunde Ishola
 
Strength of Materials iLab
Strength of Materials iLabStrength of Materials iLab
Strength of Materials iLab
Babatunde Ishola
 
Operational Amplifier iLab
Operational Amplifier iLabOperational Amplifier iLab
Operational Amplifier iLab
Babatunde Ishola
 

More from Babatunde Ishola (7)

Achieving Highly Effective Personalized Learning through Learning Objects
Achieving Highly Effective Personalized Learning through Learning ObjectsAchieving Highly Effective Personalized Learning through Learning Objects
Achieving Highly Effective Personalized Learning through Learning Objects
 
Report on the Strength of materials i lab
Report on the Strength of materials i labReport on the Strength of materials i lab
Report on the Strength of materials i lab
 
ISHOLA Babatunde Isaac (CV)
ISHOLA Babatunde Isaac (CV)ISHOLA Babatunde Isaac (CV)
ISHOLA Babatunde Isaac (CV)
 
REMOTE REALISTIC INTERFACE EXPERIMENTATION USING THE EMONA DATEX BOARD
REMOTE REALISTIC INTERFACE EXPERIMENTATION USING THE EMONA DATEX BOARDREMOTE REALISTIC INTERFACE EXPERIMENTATION USING THE EMONA DATEX BOARD
REMOTE REALISTIC INTERFACE EXPERIMENTATION USING THE EMONA DATEX BOARD
 
AN IMPROVED OPERATIONAL AMPLIFIER ILAB WITH A MORE REALISTIC LOOKING INTERFACE
AN IMPROVED OPERATIONAL AMPLIFIER ILAB WITH A MORE REALISTIC LOOKING INTERFACEAN IMPROVED OPERATIONAL AMPLIFIER ILAB WITH A MORE REALISTIC LOOKING INTERFACE
AN IMPROVED OPERATIONAL AMPLIFIER ILAB WITH A MORE REALISTIC LOOKING INTERFACE
 
Strength of Materials iLab
Strength of Materials iLabStrength of Materials iLab
Strength of Materials iLab
 
Operational Amplifier iLab
Operational Amplifier iLabOperational Amplifier iLab
Operational Amplifier iLab
 

Recently uploaded

一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
upoux
 
一比一原版(uoft毕业证书)加拿大多伦多大学毕业证如何办理
一比一原版(uoft毕业证书)加拿大多伦多大学毕业证如何办理一比一原版(uoft毕业证书)加拿大多伦多大学毕业证如何办理
一比一原版(uoft毕业证书)加拿大多伦多大学毕业证如何办理
sydezfe
 
1FIDIC-CONSTRUCTION-CONTRACT-2ND-ED-2017-RED-BOOK.pdf
1FIDIC-CONSTRUCTION-CONTRACT-2ND-ED-2017-RED-BOOK.pdf1FIDIC-CONSTRUCTION-CONTRACT-2ND-ED-2017-RED-BOOK.pdf
1FIDIC-CONSTRUCTION-CONTRACT-2ND-ED-2017-RED-BOOK.pdf
MadhavJungKarki
 
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Sinan KOZAK
 
Call For Paper -3rd International Conference on Artificial Intelligence Advan...
Call For Paper -3rd International Conference on Artificial Intelligence Advan...Call For Paper -3rd International Conference on Artificial Intelligence Advan...
Call For Paper -3rd International Conference on Artificial Intelligence Advan...
ijseajournal
 
Generative AI Use cases applications solutions and implementation.pdf
Generative AI Use cases applications solutions and implementation.pdfGenerative AI Use cases applications solutions and implementation.pdf
Generative AI Use cases applications solutions and implementation.pdf
mahaffeycheryld
 
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELDEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
ijaia
 
Height and depth gauge linear metrology.pdf
Height and depth gauge linear metrology.pdfHeight and depth gauge linear metrology.pdf
Height and depth gauge linear metrology.pdf
q30122000
 
2. protection of river banks and bed erosion protection works.ppt
2. protection of river banks and bed erosion protection works.ppt2. protection of river banks and bed erosion protection works.ppt
2. protection of river banks and bed erosion protection works.ppt
abdatawakjira
 
一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理
一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理
一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理
nedcocy
 
Object Oriented Analysis and Design - OOAD
Object Oriented Analysis and Design - OOADObject Oriented Analysis and Design - OOAD
Object Oriented Analysis and Design - OOAD
PreethaV16
 
SCALING OF MOS CIRCUITS m .pptx
SCALING OF MOS CIRCUITS m                 .pptxSCALING OF MOS CIRCUITS m                 .pptx
SCALING OF MOS CIRCUITS m .pptx
harshapolam10
 
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
ydzowc
 
5G Radio Network Througput Problem Analysis HCIA.pdf
5G Radio Network Througput Problem Analysis HCIA.pdf5G Radio Network Througput Problem Analysis HCIA.pdf
5G Radio Network Througput Problem Analysis HCIA.pdf
AlvianRamadhani5
 
Zener Diode and its V-I Characteristics and Applications
Zener Diode and its V-I Characteristics and ApplicationsZener Diode and its V-I Characteristics and Applications
Zener Diode and its V-I Characteristics and Applications
Shiny Christobel
 
TIME TABLE MANAGEMENT SYSTEM testing.pptx
TIME TABLE MANAGEMENT SYSTEM testing.pptxTIME TABLE MANAGEMENT SYSTEM testing.pptx
TIME TABLE MANAGEMENT SYSTEM testing.pptx
CVCSOfficial
 
Null Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAMNull Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAM
Divyanshu
 
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by AnantLLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
Anant Corporation
 
Software Engineering and Project Management - Software Testing + Agile Method...
Software Engineering and Project Management - Software Testing + Agile Method...Software Engineering and Project Management - Software Testing + Agile Method...
Software Engineering and Project Management - Software Testing + Agile Method...
Prakhyath Rai
 
SENTIMENT ANALYSIS ON PPT AND Project template_.pptx
SENTIMENT ANALYSIS ON PPT AND Project template_.pptxSENTIMENT ANALYSIS ON PPT AND Project template_.pptx
SENTIMENT ANALYSIS ON PPT AND Project template_.pptx
b0754201
 

Recently uploaded (20)

一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
 
一比一原版(uoft毕业证书)加拿大多伦多大学毕业证如何办理
一比一原版(uoft毕业证书)加拿大多伦多大学毕业证如何办理一比一原版(uoft毕业证书)加拿大多伦多大学毕业证如何办理
一比一原版(uoft毕业证书)加拿大多伦多大学毕业证如何办理
 
1FIDIC-CONSTRUCTION-CONTRACT-2ND-ED-2017-RED-BOOK.pdf
1FIDIC-CONSTRUCTION-CONTRACT-2ND-ED-2017-RED-BOOK.pdf1FIDIC-CONSTRUCTION-CONTRACT-2ND-ED-2017-RED-BOOK.pdf
1FIDIC-CONSTRUCTION-CONTRACT-2ND-ED-2017-RED-BOOK.pdf
 
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
 
Call For Paper -3rd International Conference on Artificial Intelligence Advan...
Call For Paper -3rd International Conference on Artificial Intelligence Advan...Call For Paper -3rd International Conference on Artificial Intelligence Advan...
Call For Paper -3rd International Conference on Artificial Intelligence Advan...
 
Generative AI Use cases applications solutions and implementation.pdf
Generative AI Use cases applications solutions and implementation.pdfGenerative AI Use cases applications solutions and implementation.pdf
Generative AI Use cases applications solutions and implementation.pdf
 
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELDEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
 
Height and depth gauge linear metrology.pdf
Height and depth gauge linear metrology.pdfHeight and depth gauge linear metrology.pdf
Height and depth gauge linear metrology.pdf
 
2. protection of river banks and bed erosion protection works.ppt
2. protection of river banks and bed erosion protection works.ppt2. protection of river banks and bed erosion protection works.ppt
2. protection of river banks and bed erosion protection works.ppt
 
一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理
一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理
一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理
 
Object Oriented Analysis and Design - OOAD
Object Oriented Analysis and Design - OOADObject Oriented Analysis and Design - OOAD
Object Oriented Analysis and Design - OOAD
 
SCALING OF MOS CIRCUITS m .pptx
SCALING OF MOS CIRCUITS m                 .pptxSCALING OF MOS CIRCUITS m                 .pptx
SCALING OF MOS CIRCUITS m .pptx
 
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
 
5G Radio Network Througput Problem Analysis HCIA.pdf
5G Radio Network Througput Problem Analysis HCIA.pdf5G Radio Network Througput Problem Analysis HCIA.pdf
5G Radio Network Througput Problem Analysis HCIA.pdf
 
Zener Diode and its V-I Characteristics and Applications
Zener Diode and its V-I Characteristics and ApplicationsZener Diode and its V-I Characteristics and Applications
Zener Diode and its V-I Characteristics and Applications
 
TIME TABLE MANAGEMENT SYSTEM testing.pptx
TIME TABLE MANAGEMENT SYSTEM testing.pptxTIME TABLE MANAGEMENT SYSTEM testing.pptx
TIME TABLE MANAGEMENT SYSTEM testing.pptx
 
Null Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAMNull Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAM
 
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by AnantLLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
 
Software Engineering and Project Management - Software Testing + Agile Method...
Software Engineering and Project Management - Software Testing + Agile Method...Software Engineering and Project Management - Software Testing + Agile Method...
Software Engineering and Project Management - Software Testing + Agile Method...
 
SENTIMENT ANALYSIS ON PPT AND Project template_.pptx
SENTIMENT ANALYSIS ON PPT AND Project template_.pptxSENTIMENT ANALYSIS ON PPT AND Project template_.pptx
SENTIMENT ANALYSIS ON PPT AND Project template_.pptx
 

Design patterns: template method

  • 2. Template Method Template method defines the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure
  • 3. Abstract Class Abstract methods that defines the basic steps of the algorithm with ‘main’ method is public and defines the algorithm structure (skeleton) deferring actual implementation to subclasses
  • 4. Components Abstract methods (must override) Non-abstract methods (can’t override) Hook methods (may override - abstract) Need a convention to separate Abstract from Hook methods (for example, DoMethod() may signify that this is an abstract method that must be implemented)
  • 5. Subclasses Implements the abstract methods into real actions Subclasses implementation may differ. Subclasses can override/redefine certain steps of an algorithm but algorithm’s structure remains intact
  • 6.
  • 7. Strength Changing behaviours - subclasses implements specific behaviour Avoids code duplication - overall work flow is implemented once Control - specifies what can and can’t change. Only specific things are allowed to change
  • 8. Code Sample abstract class Generalization { // 1. Standardize the skeleton of an algorithm in a "template" method public void findSolution() { stepOne(); stepTwo(); stepThr(); stepFor(); } // 2. Common implementations of individual steps are defined in base class protected void stepOne() { System.out.println( "Generalization.stepOne" ); } // 3. Steps requiring peculiar impls are ";placeholders" in the base class abstract protected void stepTwo(); abstract protected void stepThr(); protected void stepFor() { System.out.println( "Generalization.stepFor" ); } }
  • 9. Code Sample (contd) abstract class Specialization extends Generalization { // 4. Derived classes can override placeholder methods // 1. Standardize the skeleton of an algorithm in a "template" method protected void stepThr() { step3_1(); step3_2(); step3_3(); } // 2. Common implementations of individual steps are defined in base class protected void step3_1() { System.out.println( "Specialization.step3_1" ); } // 3. Steps requiring peculiar impls are "placeholders" in the base class abstract protected void step3_2(); protected void step3_3() { System.out.println( "Specialization.step3_3" ); } }
  • 10. Code Sample (contd) class Realization extends Specialization { // 4. Derived classes can override placeholder methods protected void stepTwo() { System.out.println( "Realization .stepTwo" ); } protected void step3_2() { System.out.println( "Realization .step3_2" ); } // 5. Derived classes can override implemented methods // 6. Derived classes can override and "call back to" base class methods protected void stepFor() { System.out.println( "Realization .stepFor" ); super.stepFor(); } } class TemplateMethodDemo { public static void main( String[] args ) { Generalization algorithm = new Realization(); algorithm.findSolution(); } }
  • 12. Real world Implementation abstract class Game { protected int playersCount; abstract void initializeGame(); abstract void makePlay(int player); abstract boolean endOfGame(); abstract void printWinner(); /* 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(); } }
  • 13. Real world Implementation //Now we can extend this class in order //to implement actual games: class Monopoly extends Game { /* Implementation of necessary concrete methods */ 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 } void printWinner() { // Display who won } /* Specific declarations for the Monopoly game. */ }
  • 14. Real World Implementation class Chess extends Game { /* Implementation of necessary concrete methods */ 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 } void printWinner() { // Display the winning player } /* Specific declarations for the chess game. */ // ... }
  • 15. ..and the one-liner The Template pattern does compile-time algorithm selection by subclassing.