Template Method By: Mahmoodreza Jahanseir Amirkabir University of Technology Computer Engineering Department Fall 2010.

Slides:



Advertisements
Similar presentations
Design Patterns Section 7.1 (JIA’s) Section (till page 259) (JIA’s) Section 7.2.2(JIA’s) Section (JIA’s)
Advertisements

Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved8-2 Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
Behavioral Pattern: Template Method C h a p t e r 5 – P a g e 217 On occasion, two different components in a software system will have significant similarities,
ITEC200 – Week03 Inheritance and Class Hierarchies.
Reza Gorgan Mohammadi AmirKabir University of Technology, Department of Computer Engineering & Information Technology Advanced design.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Iterators T.J. Niglio Computer & Systems Engineering Fall 2003 Software Design & Documentation Object Behavioral.
Patterns Lecture 2. Singleton Ensure a class only has one instance, and provide a global point of access to it.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Design Pattern Course Builder Pattern 1 Mahdieh Monzavi AmirKabir University of Technology, Department of Computer Engineering & Information Technology.
June 1, 2000 Object Oriented Programming in Java (95-707) Java Language Basics 1 Lecture 3 Object Oriented Programming in Java Language Basics Classes,
Design Patterns William A. Hoffman NYU OOP Class.
The Template Method By Sinclair Schuller. What is the Template Method? “Skeleton” definition of an algorithm Allows redefinition of predetermined points.
Interpreter By: Mahmoodreza Jahanseir Amirkabir University of Technology Computer Engineering Department Fall 2010.
Inheritance using Java
JUnit The framework. Goal of the presentation showing the design and construction of JUnit, a piece of software with proven value.
Template method. RHS – SOC 2 How to make a pizza If you order a pizza, the manufacturing of a pizza goes through certain steps We can write up a sort.
REFACTORING Lecture 4. Definition Refactoring is a process of changing the internal structure of the program, not affecting its external behavior and.
Design Patterns.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
MIT AITI 2002 Abstract Classes, Interfaces. Abstract Classes What is an abstract class? An abstract class is a class in which one or more methods is declared,
Lecture 8 Inheritance Richard Gesick. 2 OBJECTIVES How inheritance promotes software reusability. The concepts of base classes and derived classes. To.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
1 GoF Template Method (pp ) GoF Strategy (pp ) PH Single User Protection (pp ) Presentation by Julie Betlach 6/08/2009.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Template Design Pattern Kalim Baig. Summary What is Template? What is Template? Definition Definition Problem Problem How might it help the designer How.
12/6/20041 The Factory Method Pattern Presenters 王世賀 F 陳祐毓 F 張峻銘 F 吳佩達 F 林俊成 F 鄭榮智 F 許書豪 F
ECE450 - Software Engineering II1 ECE450 – Software Engineering II Today: Design Patterns IX Interpreter, Mediator, Template Method recap.
The Factory Patterns SE-2811 Dr. Mark L. Hornick 1.
Chapter 38 Persistence Framework with Patterns 1CS6359 Fall 2011 John Cole.
Linzhang Wang Dept. of Computer Sci&Tech, Nanjing University The Command Pattern.
Define an interface for creating an object, but let subclasses decide which class to instantiate Factory Method Pattern.
The Factory Method Design Pattern Motivation: Class / Type separation – Abstract class serves as type definition and concrete class provides implementation.
Factory Method Explained. Intent  Define an interface for creating an object, but let subclasses decide which class to instantiate.  Factory Method.
Define an interface for creating an object, but let subclasses decide which class to instantiate.
Creational Pattern: Factory Method At times, a framework is needed to standardize the behavior of objects that are used in a range of applications, while.
Template Methods Ordering What We Do. Example - Solitaire Initialization of many solitaire games follow this pattern: Shuffle the cards Layout the game.
Interfaces About Interfaces Interfaces and abstract classes provide more structured way to separate interface from implementation
Design Patterns Introduction
BEHAVIORAL PATTERNS 13-Sep-2012 Presenters Sanjeeb Kumar Nanda & Shankar Gogada.
The Template Method Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
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.
Banaras Hindu University. A Course on Software Reuse by Design Patterns and Frameworks.
CLASSIFICATION OF DESIGN PATTERNS Hladchuk Maksym.
TEMPLATE METHOD DESIGN PATTERN -SWAPNIL SHAH. WHAT IS A DESIGN PATTERN… A design pattern is a general reusable solution to a commonly occurring problem.
Abstract classes only used as base class from which other classes can be inherit cannot be used to instantiate any objects are incomplete Classes that.
Design Patterns: MORE Examples
Sections Inheritance and Abstract Classes
Template Method Pattern Iterator Pattern
OOP: Encapsulation &Abstraction
Factory Method Pattern
Design Patterns Lecture part 2.
University of Central Florida COP 3330 Object Oriented Programming
Factory Patterns 1.
Inheritance and Polymorphism
Behavioral Design Patterns
Software Design and Architecture
Software Design and Architecture
Object-Oriented Programming
Factory Method Pattern
Introduction to Behavioral Patterns (3)
Java Programming Language
Week 6 Object-Oriented Programming (2): Polymorphism
Strategy and Template Method Patterns, Single User Protection
Lesson 5: More on Creational Patterns
Informatics 122 Software Design II
“Don’t call us, we’ll call you”
Presentation transcript:

Template Method By: Mahmoodreza Jahanseir Amirkabir University of Technology Computer Engineering Department Fall 2010

Intent Define 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. This Pattern belongs to behavioral patterns. 2 Amirkabir University of Technology Computer Engineering Department Fall 2010

Motivation Consider an application framework that provides Application and Document classes. The Application class is responsible for opening existing documents stored in an external format, such as a file. 3 Amirkabir University of Technology Computer Engineering Department Fall 2010

Motivation (cont…) void Application::OpenDocument (const char* name) { if (!CanOpenDocument(name)) { // cannot handle this document return; } Document* doc = DoCreateDocument(); if (doc) { _docs->AddDocument(doc); AboutToOpenDocument(doc); doc->Open(); doc->DoRead(); } 4 Amirkabir University of Technology Computer Engineering Department Fall 2010

Motivation (cont…) We call OpenDocument a template method. A template method defines an algorithm in terms of abstract operations that subclasses override to provide concrete behavior. By defining some of the steps of an algorithm using abstract operations, the template method fixes their ordering, but it lets Application and Document subclasses vary those steps to suit their needs. 5 Amirkabir University of Technology Computer Engineering Department Fall 2010

Applicability To implement the invariant parts of an algorithm once and leave it up to subclasses to implement the behavior that can vary. When common behavior among subclasses should be factored and localized in a common class to avoid code duplication. This is a good example of "refactoring to generalize“. To control subclasses extensions. You can define a template method that calls "hook" operations (see Consequences) at specific points, thereby permitting extensions only at those points. 6 Amirkabir University of Technology Computer Engineering Department Fall 2010

Structure 7 Amirkabir University of Technology Computer Engineering Department Fall 2010

Participants AbstractClass (Application)  defines abstract primitive operations that concrete subclasses define to implement steps of an algorithm.  implements a template method defining the skeleton of an algorithm. The template method calls primitive operations as well as operations defined in AbstractClass or those of other objects. ConcreteClass (MyApplication)  implements the primitive operations to carry out subclass-specific steps of the algorithm. 8 Amirkabir University of Technology Computer Engineering Department Fall 2010

Collaborations ConcreteClass relies on AbstractClass to implement the invariant steps of the algorithm. 9 Amirkabir University of Technology Computer Engineering Department Fall 2010

Consequences Template methods are a fundamental technique for code reuse. They are particularly important in class libraries, because they are the means for factoring out common behavior in library classes. Template methods lead to an inverted control structure that's sometimes referred to as "the Hollywood principle," that is, "Don't call us, we'll call you“. This refers to how a parent class calls the operations of a subclass and not the other way around. 10 Amirkabir University of Technology Computer Engineering Department Fall 2010

Consequences (cont…) Template methods call the following kinds of operations:  concrete operations (either on the ConcreteClass or on client classes);  concrete AbstractClass operations (i.e., operations that are generally useful to subclasses);  primitive operations (i.e., abstract operations);  factory methods; and  hook operations, which provide default behavior that subclasses can extend if necessary. A hook operation often does nothing by default. 11 Amirkabir University of Technology Computer Engineering Department Fall 2010

Consequences (cont…) It's important for template methods to specify which operations are hooks (may be overridden) and which are abstract operations (must be overridden). To reuse an abstract class effectively, subclass writers must understand which operations are designed for overriding. A subclass can extend a parent class operation's behavior by overriding the operation and calling the parent operation explicitly: void DerivedClass::Operation () { // DerivedClass extended behavior ParentClass::Operation(); } 12 Amirkabir University of Technology Computer Engineering Department Fall 2010

Consequences (cont…) Unfortunately, it's easy to forget to call the inherited operation. We can transform such an operation into a template method to give the parent control over how subclasses extend it. The idea is to call a hook operation from a template method in the parent class. Then subclasses can then override this hook operation: void ParentClass::Operation () { // ParentClass behavior HookOperation(); } 13 Amirkabir University of Technology Computer Engineering Department Fall 2010

Consequences (cont…) HookOperation does nothing in ParentClass: void ParentClass::HookOperation () { } Subclasses override HookOperation to extend its behavior: void DerivedClass::HookOperation () { // derived class extension } 14 Amirkabir University of Technology Computer Engineering Department Fall 2010

Implementation Using C++ access control. In C++, the primitive operations that a template method calls can be declared protected members. This ensures that they are only called by the template method. Primitive operations that must be overridden are declared pure virtual. The template method itself should not be overridden; therefore you can make the template method a nonvirtual member function. Minimizing primitive operations. An important goal in designing template methods is to minimize the number of primitive operations that a subclass must override to flesh out the algorithm. The more operations that need overriding, the more tedious things get for clients. 15 Amirkabir University of Technology Computer Engineering Department Fall 2010

Implementation (cont…) Naming conventions. You can identify the operations that should be overridden by adding a prefix to their names. For example, the MacApp framework for Macintosh applications prefixes template method names with "Do-": "DoCreateDocument", "DoRead", and so forth. 16 Amirkabir University of Technology Computer Engineering Department Fall 2010

Example1 View defines two concrete operations  SetFocus: set up the drawing state  ResetFocus: clean up the drawing state  DoDisplay hook operation: performs the actual drawing. void View::Display () { SetFocus(); DoDisplay(); ResetFocus(); } void View::DoDisplay () { } void MyView::DoDisplay () { // render the view's contents } 17 Amirkabir University of Technology Computer Engineering Department Fall 2010

Example2 Suppose we have a Manufacturing class as follows: public class Manufacturing {... // A template method! public final void makePart () { operation1(); operation2(); } public void operation1() { // Default behavior for Operation 1 } public void operation2() { // Default behavior for Operation 2 }... } 18 Amirkabir University of Technology Computer Engineering Department Fall 2010

Example2 (cont…) And a subclass wants to do some behavior between operation1() and operation2() of makePart(), so it overrides operation2() as follows: public class MyManufacturing {... public void operation2() { // Put behavior we want to do BEFORE the normal Operation2 // here! super.operation2(); }... } 19 Amirkabir University of Technology Computer Engineering Department Fall 2010

Example2 (cont…) If you find that many subclasses want to do this, it is wise to modify the superclass and put in a hook operation: public class Manufacturing {... // A template method! public final void makePart () { operation1(); hook(); // A hook method operation2(); } // Do nothing hook method. public void hook() {}... } 20 Amirkabir University of Technology Computer Engineering Department Fall 2010

Example3 public abstract class RobotTemplate { public string Go() //template method { Start(); GetParts(); Assemble(); Test(); Stop(); } public abstract string GetParts(); public abstract string Assemble(); public abstract string Test(); public string Start() { /*Starting…*/ } public string Stop() { /* Stopping …*/ } } 21 Amirkabir University of Technology Computer Engineering Department Fall 2010

Example3 (cont…) public class AutomotiveRobot : RobotTemplate { public override string GetParts() { //Getting a carburetor… } public override string Assemble() { //Installing the carburetor… } public override string Test() { //Revving the engine… } Client code is as follows: RobotTemplate r=new AutomotiveRobot(); r.Go(); 22 Amirkabir University of Technology Computer Engineering Department Fall 2010

Related Patterns Factory Methods are often called by template methods. In the Motivation example, the factory method DoCreateDocument is called by the template method OpenDocument. Strategy : Template methods use inheritance to vary part of an algorithm. Strategies use delegation to vary the entire algorithm. 23 Amirkabir University of Technology Computer Engineering Department Fall 2010

Q&A Amirkabir University of Technology Computer Engineering Department Fall 2010