Behavioral Pattern: Visitor C h a p t e r 5 – P a g e 224 When an algorithm is separated from an object structure upon which it operates, new operations.

Slides:



Advertisements
Similar presentations
AUTHOR: RADU MUSCHEVICI, ETC. PRESENTED BY: LIQUAN PEI DEPARTMENT OF PHYSICS, UMASS Multiple Dispatch in Practice (OOPSLA2008)
Advertisements

C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
SWE 4743 Strategy Patterns Richard Gesick. CSE Strategy Pattern the strategy pattern (also known as the policy pattern) is a software design.
Objects and Classes First Programming Concepts. 14/10/2004Lecture 1a: Introduction 2 Fundamental Concepts object class method parameter data type.
Encapsulation, Inheritance & Interfaces CSE 115 Spring 2006 February 27, March 1 & 3, 2006.
Iterators T.J. Niglio Computer & Systems Engineering Fall 2003 Software Design & Documentation Object Behavioral.
Chapter 3 Data Abstraction: The Walls. © 2005 Pearson Addison-Wesley. All rights reserved3-2 Abstract Data Types Modularity –Keeps the complexity of a.
Collaboration Diagrams. Example Building Collaboration Diagrams.
C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects.
Software Design and Documentation Individual Presentation: Composite Pattern 9/11/03.
ECE450 - Software Engineering II1 ECE450 – Software Engineering II Today: Design Patterns VI Composite, Iterator, and Visitor Patterns.
CSE 332: C++ templates and generic programming I Motivation for Generic Programming in C++ We’ve looked at procedural programming –Reuse of code by packaging.
Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter.
Behavioral Patterns C h a p t e r 5 – P a g e 128 BehavioralPatterns Design patterns that identify and realize common interactions between objects Chain.
ASM: A Bytecode Manipulation Tool – A brief Overview Course : CSE 6329 Spring 2011 University of Texas at Arlington.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
C++ How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved. Note: C How to Program, Chapter 22 is a copy of C++ How to Program Chapter.
Chapter 3 Introduction to Collections – Stacks Modified
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
©Fraser Hutchinson & Cliff Green C++ Certificate Program C++ Intermediate Decorator, Strategy, State Patterns.
Go4 Visitor Pattern Presented By: Matt Wilson. Introduction 2  This presentation originated out of casual talk between former WMS “C++ Book Club” (defunct.
Defining New Types Lecture 21 Hartmut Kaiser
CSCI-383 Object-Oriented Programming & Design Lecture 5.
Computing IV Singleton Pattern Xinwen Fu.
Refactoring Deciding what to make a superclass or interface is difficult. Some of these refactorings are helpful. Some research items include Inheritance.
1 Object Oriented Design and UML Class Relationships –Dependency –Aggregation –Interfaces –Inheritance Interfaces Reading for this Lecture: L&L 6.4 – 6.5.
....and other creepy things from John Vlissides The Visitor Pattern EXISTS! And its INTENT is to represent an operation to be performed on the elements.
COMPUTER PROGRAMMING. Functions’ review What is a function? A function is a group of statements that is executed when it is called from some point of.
Behavioral Pattern: Strategy C h a p t e r 5 – P a g e 205 The Open-Closed Principle advocates designing software in such a way that it will absorb new.
ECE450 - Software Engineering II1 ECE450 – Software Engineering II Today: Design Patterns VIII Chain of Responsibility, Strategy, State.
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.
C++ Classes and Data Structures Jeffrey S. Childs
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Templates.
Behavioral Pattern: Iterator C h a p t e r 5 – P a g e 159 Software can become difficult to manage when a variety of different traversals of a variety.
11-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN
Object Oriented Analysis and Design Class and Object Diagrams.
QUEUES What are Queues? Creating a Queue Enqueuing and Dequeuing Testing for an Empty Queue.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
Copyright © 2002 W. A. Tucker1 Chapter 10 Lecture Notes Bill Tucker Austin Community College COSC 1315.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
The Strategy Pattern SE-2811 Dr. Mark L. Hornick 1.
Design Patterns Introduction
CS212: Object Oriented Analysis and Design Lecture 39: Design Pattern-III.
Introduction to Object-Oriented Programming Lesson 2.
The Visitor Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
Software Construction and Evolution - CSSE 375 Dealing with Generalization Steve and Shawn Left – In the 1990 movie “The Freshman,” Matthew Broderick,
1 Chapter 1 C++ Templates Readings: Sections 1.6 and 1.7.
1 Data Structures CSCI 132, Spring 2014 Lecture 2 Classes and Abstract Data Types Read Ch Read Style Guide (see course webpage)
Structure A Data structure is a collection of variable which can be same or different types. You can refer to a structure as a single variable, and to.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
Motivation for Generic Programming in C++
Eine By: Avinash Reddy 09/29/2016.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
CS 3370 – C++ Object-oriented Programming
Creational Pattern: Prototype
Chapter 14 Templates C++ How to Program, 8/e
CS3340 – OOP and C++ L. Grewe.
Student Book An Introduction
Tuesday, February 20, 2018 Announcements… For Today… 4+ For Next Time…
Friday, February 16, 2018 Announcements… For Today… 4.5-, pgs. 252
Stack Lesson xx   This module shows you the basic elements of a type of linked list called a stack.
METHODS AND BEHAVIORS AKEEL AHMED.
Chapter 11 Generic Collections
Chapter 16 Linked Structures
Context Objects Evolution of object behavior Behavioral patterns
Software Design Lecture : 39.
16. Visitors SE2811 Software Component Design
16. Visitors SE2811 Software Component Design
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
Visitor Pattern Intent
Presentation transcript:

Behavioral Pattern: Visitor C h a p t e r 5 – P a g e 224 When an algorithm is separated from an object structure upon which it operates, new operations can be added to existing object structures without modifying those structures The Visitor Pattern allows new virtual functions to be added to a family of classes without modifying the classes themselves; instead, one creates a visitor class that implements all of the appropriate specializations of the virtual function. This is particularly useful when there are a large number of instances of a small number of classes and some operation must be performed that involves all or most of them. (While powerful, the Visitor Pattern is more limited than conventional virtual functions since it isnt possible to create visitors for objects without adding a small callback method inside each class and the callback method in each of the classes is not inheritable.)

The Visitor Pattern C h a p t e r 5 – P a g e 225 The Visitor declares a visit operation for each class of ConcreteElement in the object structure. The operation's name and signature identifies the class that sends the Visit request to the visitor. That lets the visitor determine the concrete class of the element being visited. Then the visitor can access the elements directly through its particular interface. The ConcreteVisitor implements each operation declared by the Visitor. Each operation implements a fragment of the algorithm defined for the corresponding class or object in the structure. The ConcreteVisitor provides the context for the algorithm and stores its local state. This state often accumulates results during the traversal of the structure. The Element defines an Accept operation that takes a visitor as an argument, while the ConcreteElement implements an Accept operation that takes a visitor as an argument. The Object Structure can enumerate its elements and may provide a high-level interface to allow the visitor to visit its elements. It may either be a Composite (pattern) or a collection such as a list or a set.

C h a p t e r 5 – P a g e 226 Non-Software Example: Cab-Calling When a person calls a taxi company he or she becomes part of the company's list of customers (the ObjectStructure). The taxi companys dispatcher (the Client) then sends a cab (the Visitor) to the customer (the Element). Upon entering the taxi, the customer is no longer in control of his or her own transportation, the taxi (i.e., the taxi driver) is.

C h a p t e r 5 – P a g e 227 Software Example: Car Parts The Car (ObjectStructure) is composed of various CarElements (Wheels, Engine, Body). The CarElementVisitor provides an interface for visiting each type of CarElement. The DiagnosticVisitor and the TestDriveVisitor implement specific algorithms for dealing with the Cars CarElements without altering the definitions of the Car or the CarElements.

C h a p t e r 5 – P a g e 228 Car Parts Visitor Pattern C++ Code #include using namespace std; class Wheel; class Engine; class Body; class Car; // Interface to all car parts struct CarElementVisitor { virtual void visit(Wheel& wheel) const = 0; virtual void visit(Engine& engine) const = 0; virtual void visit(Body& body) const = 0; virtual void visitCar(Car& car) const = 0; virtual ~CarElementVisitor() {} }; // Interface to one car part struct CarElement { virtual void accept(const CarElementVisitor& visitor) = 0; virtual ~CarElement() {} };

C h a p t e r 5 – P a g e 229 // Wheel element, there are four wheels with unique names class Wheel : public CarElement { public: explicit Wheel(const string& name) : name(name) {} const string& getName() const { return name; } void accept(const CarElementVisitor& visitor) { visitor.visit(*this); } private: string name; }; // Engine element class Engine : public CarElement { public: void accept(const CarElementVisitor& visitor) { visitor.visit(*this); } }; // Body element class Body : public CarElement { public: void accept(const CarElementVisitor& visitor) { visitor.visit(*this); } };

C h a p t e r 5 – P a g e 230 // Car, all car elements (parts) together in one vector class Car { public: vector & getElements() { return elements; } Car() { // assume that neither push_back nor Wheel(const string&) may throw elements.push_back( new Wheel("front left") ); elements.push_back( new Wheel("front right") ); elements.push_back( new Wheel("back left") ); elements.push_back( new Wheel("back right") ); elements.push_back( new Body() ); elements.push_back( new Engine() ); } ~Car() { vector ::iterator it; for (it = elements.begin(); it != elements.end(); ++it) { delete *it; } private: vector elements; };

C h a p t e r 5 – P a g e 231 // DiagnosticVisitor adds a diagnostic capability to the // Car class without modifying the Car class itself. class CarElementDiagnosticVisitor : public CarElementVisitor { public: void visit(Wheel& wheel) const { cout << "Testing the car's " << wheel.getName() << " wheel for tread and punctures" << endl; } void visit(Engine& engine) const { cout << "Examining the car's engine for leaks and loose belts" << endl; } void visit(Body& body) const { cout << "Examining the car's body for dents and scratches" << endl; } void visitCar(Car& car) const { cout << "Performing diagnostic testing on the car" << endl; vector & elems = car.getElements(); // Cycle through the car's elements, issuing a // callback from each car element to this visitor. vector ::iterator it; for (it = elems.begin(); it != elems.end(); ++it ) { (*it)->accept(*this); } cout << "Diagnostic testing complete" << endl << endl; } };

C h a p t e r 5 – P a g e 232 // TestDriveVisitor adds a test drive capability to the // Car class without modifying the Car class itself. class CarElementTestDriveVisitor : public CarElementVisitor { public: void visit(Wheel& wheel) const { cout << "Kicking the car's " << wheel.getName() << " tire" << endl; } void visit(Engine& engine) const { cout << "Starting the car's engine" << endl; } void visit(Body& body) const { cout << "Driving the car for a road test" << endl; } void visitCar(Car& car) const { cout << "Test driving the car" << endl; vector & elems = car.getElements(); // Cycle through the car's elements, issuing a // callback from each car element to this visitor. vector ::iterator it; for (it = elems.begin(); it != elems.end(); ++it ) { (*it)->accept(*this); } cout << "Test drive complete" << endl << endl; } };

C h a p t e r 5 – P a g e 233 void main() { Car car; CarElementDiagnosticVisitor printVisitor; CarElementTestDriveVisitor doVisitor; printVisitor.visitCar(car); doVisitor.visitCar(car); }

Visitor Pattern Advantages C h a p t e r 5 – P a g e 234 The Visitor Pattern permits the addition of functions to class libraries for which either the source code or the ability to change the source code is unavailable. This pattern is also helpful when it is necessary to obtain data from a disparate collection of unrelated classes and use it to present the results of a global calculation to the user program. It can be used to gather related operations into a single class rather than forcing the designer to change or derive classes to add these operations.