SlideShare una empresa de Scribd logo
1 de 18
Chapter 8: The Template
Method Pattern
StarBuzz
• Coffee Recipe
– Boil some water
– Brew coffee in boiling water
– Pour coffee in cup
– Add sugar and milk
• Tea Recipe
– Boil some water
– Steep tea in boiling water
– Pour tea in cup
– Add lemon
• Suppose you are required to implement a system to
maintain this
Problems with the Solution
• Code is duplicated across the classes – code
changes would have to be made in more than
one place.
• Adding a new beverage would result in further
duplication.
• Knowledge of the algorithm and
implementation is distributed over classes.
More General Approach
• Both subclasses inherit a general algorithm.
• Some methods in the algorithm are concrete,
i.e. methods that perform the same actions
for all subclasses.
• Other methods in the algorithm are abstract,
i.e. methods that perform class-specific
actions.
Class Diagram for the New
Approach
Caffeine Beverage
{Abstract}
boilWater()
pourInCup()
prepareRecipe()
NewTea
brewCoffeeGrinds()
addSugarAndMilk()
NewCoffee
steepTeaBag()
addLemon()
prepareRecipe() prepareRecipe()
Abstracting Prepare Recipe
Caffeine Beverage
{Abstract}
boilWater()
brew()
pourInCup()
addCondiments()
prepareRecipe()
NewTea
brew()
addCondiments()
NewCoffee
brew()
addCondiments()
Advantages of the New Approach
• A single class protects and controls the
algorithm, namely, CaffeineBeverage.
• The superclass facilitates reuse of methods.
• Code changes will occur in only one place.
• Other beverages can be easily added.
This is the Template Pattern
• The prepareRecipe() method implements the template
pattern.
• This method serves as a template for an algorithm,
namely that for making a caffeinated beverage.
• In the template each step is represented by a method.
• Some methods are implemented in the superclass.
• Other method must be implemented by the subclass
and are declared abstract.
• The template pattern defines the steps of an algorithm
and allows the subclasses to implement one or more
of the steps.
Template Pattern
• Encapsulates an algorithm by creating a template
for it.
• Defines the skeleton of an algorithm as a set of
steps.
• Some methods of the algorithm have to be
implemented by the subclasses – these are
abstract methods in the super class.
• The subclasses can redefine certain steps of the
algorithm without changing the algorithm’s
structure.
• Some steps of the algorithm are concrete
methods defined in the super class.
Template Pattern Structure
AbstractClass
primitiveOperation1()
...
primitiveOperationN()
templateMethod()
ConcreteClass
primitiveOperation1()
...
...
primitiveOperationN()
concreteOperations
Code for the Template
public abstract class AbstractClass
{
final void templateMethod()
{
primitiveOperation1();
primitiveOperation2();
concreteOperation();
}
abstract void primitiveOperation1();
abstract void primitiveOperation2();
void concreteOperation()
{
//Implementation
}
}
Using Hooks
• We want to minimize the number of abstract
methods used.
• Thus, the steps of the algorithm should not be
too granular.
• However, less granularity means less flexibility.
• Hooks are methods which can be overridden by
subclasses, however this is optional.
• Example: Suppose the customer is given an
option as to whether they would like condiments
or not.
Why Hooks
• The number of abstract methods used must
be minimized.
• Enables a subclass to implement an optional
part of an algorithm.
• Enables a subclass to react to a step in the
template method.
• Enables the subclass to make a decision for
the abstract class.
Examples of Using Hooks in the Java
API
• JFrame hooks
– paint()
• Applet hooks
– init()
– repaint()
– start()
– stop()
– destroy()
– paint()
Hollywood Principle
• The template pattern follows the hollywood
principle.
• Principle: Don’t call us, we will call you.
• Low-level components are activated by high-level
components.
• A low-level component never calls a high-level
component.
• In the template pattern the abstract class is the
high-level component and the concrete classes
the low-level components.
Sorting Using the Template Pattern
• Java’s Array class provides a template method for sorting.
• The sort is a merge sort and requires a method compareTo().
• Code:
public static void sort(Object a[]){
Object aux[] = (Object a[])a.clone);
mergeSort(aux,a,0,a.length,0);
}
private static void mergeSort(Object src[], Object dest[], int low,int
high, int off)
{
for(int i=low; i < high; ++i){
for(int j=i; j < low; &&
((Comparable)dest[j-1).compareTo((Comparable)dest[j])>0;j--)
{
swap(dest, j, j-1);
}
}
return;
}
Sorting Ducks
• The Duck class must implement the
Comparable interface.
• The Duck class must implement a
compareTo() method.
• Store the Duck instances in an array.
• Use the Array class sort to sort the array.
In Summary…
• Design Principle: Don’t call us we’ll call you.
• Template pattern defines steps of an
algorithm.
• Subclasses cannot change the algorithm - final
• Facilitates code reuse.
• Similar to the strategy pattern.
• The factory pattern is a specialization of the
template pattern.

Más contenido relacionado

La actualidad más candente

Behavioral design patterns presentation
Behavioral design patterns presentationBehavioral design patterns presentation
Behavioral design patterns presentationMina Ayoub
 
Analysis of a basic java program
Analysis of a basic java programAnalysis of a basic java program
Analysis of a basic java programSujit Kumar
 
Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)paramisoft
 
Factory Method Design Pattern
Factory Method Design PatternFactory Method Design Pattern
Factory Method Design Patternmelbournepatterns
 
RapidMiner: Advanced Processes And Operators
RapidMiner:  Advanced Processes And OperatorsRapidMiner:  Advanced Processes And Operators
RapidMiner: Advanced Processes And OperatorsDataminingTools Inc
 
ASM Core API - methods (part 1)
ASM Core API - methods (part 1)ASM Core API - methods (part 1)
ASM Core API - methods (part 1)TaegeonLee1
 
01 introduction to struts2
01 introduction to struts201 introduction to struts2
01 introduction to struts2Smita B Kumar
 
Factory Design Pattern
Factory Design PatternFactory Design Pattern
Factory Design PatternJaswant Singh
 
Chapter 05 polymorphism extra
Chapter 05 polymorphism extraChapter 05 polymorphism extra
Chapter 05 polymorphism extraNurhanna Aziz
 
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
 
OOP with Java - Abstract Classes and Interfaces
OOP with Java - Abstract Classes and InterfacesOOP with Java - Abstract Classes and Interfaces
OOP with Java - Abstract Classes and InterfacesRatnaJava
 
Struts2
Struts2Struts2
Struts2yuvalb
 
Java findamentals2
Java findamentals2Java findamentals2
Java findamentals2Todor Kolev
 
Exception Handling in C#
Exception Handling in C#Exception Handling in C#
Exception Handling in C#Abid Kohistani
 

La actualidad más candente (16)

Behavioral design patterns presentation
Behavioral design patterns presentationBehavioral design patterns presentation
Behavioral design patterns presentation
 
Factory Design Pattern
Factory Design PatternFactory Design Pattern
Factory Design Pattern
 
Analysis of a basic java program
Analysis of a basic java programAnalysis of a basic java program
Analysis of a basic java program
 
Command Pattern in Ruby
Command Pattern in RubyCommand Pattern in Ruby
Command Pattern in Ruby
 
Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)
 
Factory Method Design Pattern
Factory Method Design PatternFactory Method Design Pattern
Factory Method Design Pattern
 
RapidMiner: Advanced Processes And Operators
RapidMiner:  Advanced Processes And OperatorsRapidMiner:  Advanced Processes And Operators
RapidMiner: Advanced Processes And Operators
 
ASM Core API - methods (part 1)
ASM Core API - methods (part 1)ASM Core API - methods (part 1)
ASM Core API - methods (part 1)
 
01 introduction to struts2
01 introduction to struts201 introduction to struts2
01 introduction to struts2
 
Factory Design Pattern
Factory Design PatternFactory Design Pattern
Factory Design Pattern
 
Chapter 05 polymorphism extra
Chapter 05 polymorphism extraChapter 05 polymorphism extra
Chapter 05 polymorphism extra
 
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?
 
OOP with Java - Abstract Classes and Interfaces
OOP with Java - Abstract Classes and InterfacesOOP with Java - Abstract Classes and Interfaces
OOP with Java - Abstract Classes and Interfaces
 
Struts2
Struts2Struts2
Struts2
 
Java findamentals2
Java findamentals2Java findamentals2
Java findamentals2
 
Exception Handling in C#
Exception Handling in C#Exception Handling in C#
Exception Handling in C#
 

Similar a Chapter8

METHODS IN JAVA.ppt
METHODS IN  JAVA.pptMETHODS IN  JAVA.ppt
METHODS IN JAVA.pptJayanthiM15
 
Introduction to c first week slides
Introduction to c first week slidesIntroduction to c first week slides
Introduction to c first week slidesluqman bawany
 
Concurrency Programming in Java - 02 - Essentials of Java Part 1
Concurrency Programming in Java - 02 - Essentials of Java Part 1Concurrency Programming in Java - 02 - Essentials of Java Part 1
Concurrency Programming in Java - 02 - Essentials of Java Part 1Sachintha Gunasena
 
StackNet Meta-Modelling framework
StackNet Meta-Modelling frameworkStackNet Meta-Modelling framework
StackNet Meta-Modelling frameworkSri Ambati
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.Tarunsingh198
 
Abstraction in java.pptx
Abstraction in java.pptxAbstraction in java.pptx
Abstraction in java.pptxAsifMulani17
 
Few minutes To better Code - Refactoring
Few minutes To better Code - RefactoringFew minutes To better Code - Refactoring
Few minutes To better Code - RefactoringDiaa Al-Salehi
 
The maze of Design Patterns & SOLID Principles
The maze of Design Patterns & SOLID PrinciplesThe maze of Design Patterns & SOLID Principles
The maze of Design Patterns & SOLID PrinciplesMuhammad Raza
 
Java tutorials
Java tutorialsJava tutorials
Java tutorialssaryu2011
 
Md06 advance class features
Md06 advance class featuresMd06 advance class features
Md06 advance class featuresRakesh Madugula
 
Super Keyword in Java.pptx
Super Keyword in Java.pptxSuper Keyword in Java.pptx
Super Keyword in Java.pptxKrutikaWankhade1
 
class as the basis.pptx
class as the basis.pptxclass as the basis.pptx
class as the basis.pptxEpsiba1
 
Java For beginners and CSIT and IT students
Java  For beginners and CSIT and IT studentsJava  For beginners and CSIT and IT students
Java For beginners and CSIT and IT studentsPartnered Health
 

Similar a Chapter8 (20)

Design p atterns
Design p atternsDesign p atterns
Design p atterns
 
Lambdas in Java 8
Lambdas in Java 8Lambdas in Java 8
Lambdas in Java 8
 
METHODS IN JAVA.ppt
METHODS IN  JAVA.pptMETHODS IN  JAVA.ppt
METHODS IN JAVA.ppt
 
Introduction to c first week slides
Introduction to c first week slidesIntroduction to c first week slides
Introduction to c first week slides
 
Concurrency Programming in Java - 02 - Essentials of Java Part 1
Concurrency Programming in Java - 02 - Essentials of Java Part 1Concurrency Programming in Java - 02 - Essentials of Java Part 1
Concurrency Programming in Java - 02 - Essentials of Java Part 1
 
Design Patterns - GOF
Design Patterns - GOFDesign Patterns - GOF
Design Patterns - GOF
 
Ch5 inheritance
Ch5 inheritanceCh5 inheritance
Ch5 inheritance
 
StackNet Meta-Modelling framework
StackNet Meta-Modelling frameworkStackNet Meta-Modelling framework
StackNet Meta-Modelling framework
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.
 
Abstraction in java.pptx
Abstraction in java.pptxAbstraction in java.pptx
Abstraction in java.pptx
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Few minutes To better Code - Refactoring
Few minutes To better Code - RefactoringFew minutes To better Code - Refactoring
Few minutes To better Code - Refactoring
 
template method.pptx
template method.pptxtemplate method.pptx
template method.pptx
 
The maze of Design Patterns & SOLID Principles
The maze of Design Patterns & SOLID PrinciplesThe maze of Design Patterns & SOLID Principles
The maze of Design Patterns & SOLID Principles
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
 
Md06 advance class features
Md06 advance class featuresMd06 advance class features
Md06 advance class features
 
Super Keyword in Java.pptx
Super Keyword in Java.pptxSuper Keyword in Java.pptx
Super Keyword in Java.pptx
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
class as the basis.pptx
class as the basis.pptxclass as the basis.pptx
class as the basis.pptx
 
Java For beginners and CSIT and IT students
Java  For beginners and CSIT and IT studentsJava  For beginners and CSIT and IT students
Java For beginners and CSIT and IT students
 

Último

AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024The Digital Insurer
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Principled Technologies
 

Último (20)

AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 

Chapter8

  • 1. Chapter 8: The Template Method Pattern
  • 2. StarBuzz • Coffee Recipe – Boil some water – Brew coffee in boiling water – Pour coffee in cup – Add sugar and milk • Tea Recipe – Boil some water – Steep tea in boiling water – Pour tea in cup – Add lemon • Suppose you are required to implement a system to maintain this
  • 3. Problems with the Solution • Code is duplicated across the classes – code changes would have to be made in more than one place. • Adding a new beverage would result in further duplication. • Knowledge of the algorithm and implementation is distributed over classes.
  • 4. More General Approach • Both subclasses inherit a general algorithm. • Some methods in the algorithm are concrete, i.e. methods that perform the same actions for all subclasses. • Other methods in the algorithm are abstract, i.e. methods that perform class-specific actions.
  • 5. Class Diagram for the New Approach Caffeine Beverage {Abstract} boilWater() pourInCup() prepareRecipe() NewTea brewCoffeeGrinds() addSugarAndMilk() NewCoffee steepTeaBag() addLemon() prepareRecipe() prepareRecipe()
  • 6. Abstracting Prepare Recipe Caffeine Beverage {Abstract} boilWater() brew() pourInCup() addCondiments() prepareRecipe() NewTea brew() addCondiments() NewCoffee brew() addCondiments()
  • 7. Advantages of the New Approach • A single class protects and controls the algorithm, namely, CaffeineBeverage. • The superclass facilitates reuse of methods. • Code changes will occur in only one place. • Other beverages can be easily added.
  • 8. This is the Template Pattern • The prepareRecipe() method implements the template pattern. • This method serves as a template for an algorithm, namely that for making a caffeinated beverage. • In the template each step is represented by a method. • Some methods are implemented in the superclass. • Other method must be implemented by the subclass and are declared abstract. • The template pattern defines the steps of an algorithm and allows the subclasses to implement one or more of the steps.
  • 9. Template Pattern • Encapsulates an algorithm by creating a template for it. • Defines the skeleton of an algorithm as a set of steps. • Some methods of the algorithm have to be implemented by the subclasses – these are abstract methods in the super class. • The subclasses can redefine certain steps of the algorithm without changing the algorithm’s structure. • Some steps of the algorithm are concrete methods defined in the super class.
  • 11. Code for the Template public abstract class AbstractClass { final void templateMethod() { primitiveOperation1(); primitiveOperation2(); concreteOperation(); } abstract void primitiveOperation1(); abstract void primitiveOperation2(); void concreteOperation() { //Implementation } }
  • 12. Using Hooks • We want to minimize the number of abstract methods used. • Thus, the steps of the algorithm should not be too granular. • However, less granularity means less flexibility. • Hooks are methods which can be overridden by subclasses, however this is optional. • Example: Suppose the customer is given an option as to whether they would like condiments or not.
  • 13. Why Hooks • The number of abstract methods used must be minimized. • Enables a subclass to implement an optional part of an algorithm. • Enables a subclass to react to a step in the template method. • Enables the subclass to make a decision for the abstract class.
  • 14. Examples of Using Hooks in the Java API • JFrame hooks – paint() • Applet hooks – init() – repaint() – start() – stop() – destroy() – paint()
  • 15. Hollywood Principle • The template pattern follows the hollywood principle. • Principle: Don’t call us, we will call you. • Low-level components are activated by high-level components. • A low-level component never calls a high-level component. • In the template pattern the abstract class is the high-level component and the concrete classes the low-level components.
  • 16. Sorting Using the Template Pattern • Java’s Array class provides a template method for sorting. • The sort is a merge sort and requires a method compareTo(). • Code: public static void sort(Object a[]){ Object aux[] = (Object a[])a.clone); mergeSort(aux,a,0,a.length,0); } private static void mergeSort(Object src[], Object dest[], int low,int high, int off) { for(int i=low; i < high; ++i){ for(int j=i; j < low; && ((Comparable)dest[j-1).compareTo((Comparable)dest[j])>0;j--) { swap(dest, j, j-1); } } return; }
  • 17. Sorting Ducks • The Duck class must implement the Comparable interface. • The Duck class must implement a compareTo() method. • Store the Duck instances in an array. • Use the Array class sort to sort the array.
  • 18. In Summary… • Design Principle: Don’t call us we’ll call you. • Template pattern defines steps of an algorithm. • Subclasses cannot change the algorithm - final • Facilitates code reuse. • Similar to the strategy pattern. • The factory pattern is a specialization of the template pattern.