Go4 Visitor Pattern Presented By: Matt Wilson. Introduction 2  This presentation originated out of casual talk between former WMS “C++ Book Club” (defunct.

Slides:



Advertisements
Similar presentations
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.
Advertisements

CS 350 – Software Design The Bridge Pattern – Chapter 10 Most powerful pattern so far. Gang of Four Definition: Decouple an abstraction from its implementation.
Inheritance Inheritance Reserved word protected Reserved word super
Bag implementation Add(T item) – Enlarge bag if necessary; allocate larger array Remove(T item) – Reduce bag if necessary; allocate smaller array Iterator.
© Lethbridge/Laganière 2001 Chapter 9: Architecting and designing software1 Layers Data from IBM-Rational and Craig Larman…
CS 106 Introduction to Computer Science I 05 / 03 / 2010 Instructor: Michael Eckmann.
Iterators T.J. Niglio Computer & Systems Engineering Fall 2003 Software Design & Documentation Object Behavioral.
Visitor Pattern Jeff Schott CS590L Spring What is the Purpose of the Visitor Pattern ? n Represent an operation to be performed on the elements.
Design Patterns 2 Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
Visitor Matt G. Ellis. Intent Metsker: Let developers define a new operation for a hierarchy without changing the hierarchy classes. GoF: Represent an.
ECE450 - Software Engineering II1 ECE450 – Software Engineering II Today: Design Patterns VI Composite, Iterator, and Visitor Patterns.
5.0 Objects First with Java A Practical Introduction using BlueJ David J. Barnes Michael Kölling.
3/15/05H-1 © 2001 T. Horton CS 494 Object-Oriented Analysis & Design Evaluating Class Diagrams Topics include: Cohesion, Coupling Law of Demeter (handout)
What Is a Factory Pattern?.  Factories are classes that create or construct something.  In the case of object-oriented code languages, factories construct.
CSE 331 Software Design & Implementation Hal Perkins Winter 2013 Design Patterns Part 3 (Slides by Mike Ernst and David Notkin) 1.
Abstraction, Inheritance, and Polymorphism in Java.
Starting Chapter 4 Starting. 1 Course Outline* Covered in first half until Dr. Li takes over. JAVA and OO: Review what is Object Oriented Programming.
CS 106 Introduction to Computer Science I 04 / 13 / 2007 Friday the 13 th Instructor: Michael Eckmann.
GRASP Principles. How to Design Objects The hard step: moving from analysis to design How to do it? –Design principles (Larman: “patterns”) – an attempt.
Design Dan Fleck CS 421 George Mason University. What is the design phase? Analysis phase describes what the system should do Analysis has provided a.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Marcus Frean.
SE2811 Week 7, Class 1 Composite Pattern Applications Conceptual form Class structure Coding Example Lab Thursday: Quiz SE-2811 Slide design: Dr. Mark.
Tech Talk Go4 Factory Patterns Presented By: Matt Wilson.
Design Design and Software Architecture. The design phase The analysis phase describes what the system should be doing The design phase describes how.
Chapter 9: The Iterator Pattern
CS 350 – Software Design The Strategy Pattern – Chapter 9 Changes to software, like other things in life, often focus on the immediate concerns and ignore.
Introduction CS 3358 Data Structures. What is Computer Science? Computer Science is the study of algorithms, including their  Formal and mathematical.
1-1 C Sc 335 Course Overview Object-Oriented Programming and Design Rick Mercer.
Lexi case study (Part 2) Presentation by Matt Deckard.
Genericity Ranga Rodrigo Based on Mark Priestley's Lectures.
Design Patterns Gang Qian Department of Computer Science University of Central Oklahoma.
Refactoring 2. Admin Blackboard Quiz Acknowledgements Material in this presentation was drawn from Martin Fowler, Refactoring: Improving the Design of.
Chapter 7: The Adapter Pattern. Object Oriented Adapters Suppose that you have existing software. You have outsourced some of your work and there is a.
Behavioral Patterns CSE301 University of Sunderland Harry R Erwin, PhD.
CS 210 Final Review November 28, CS 210 Adapter Pattern.
CS212: Object Oriented Analysis and Design Lecture 39: Design Pattern-III.
The Visitor Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
Go4 Template Method, Strategy, State Patterns Presented By: Matt Wilson.
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
CS 210 Iterator Pattern October 31 st, Example to motivate discussion We have two lists (of menu items) one implemented using ArrayList and another.
Data Design and Implementation. Definitions Atomic or primitive type A data type whose elements are single, non-decomposable data items Composite type.
Example to motivate discussion We have two lists (of menu items) one implemented using ArrayList and another using Arrays. How does one work with these.
Watching the movie the hard way…. Page 256 – Head First Design Patterns.
Iterator Pattern. Traversing two different collections  When bringing two previously developed objects together, it can be difficult to change an implementation.
CS 210 Proxy Pattern Nov 16 th, RMI – A quick review A simple, easy to understand tutorial is located here:
Design Patterns (II) Lecture Three. Solution to Homework Two Used framework Used design patterns: composite and state Question: what are the differences.
CS 350 – Software Design The Decorator Pattern – Chapter 17 In this chapter we expand our e-commerce case study and learn how to use the Decorator Pattern.
The Visitor Design Pattern. What’s It All About? Allows for new operations to be defined and used on elements of an object structure with out changing.
3/1/01H-1 © 2001 T. Horton CS 494 Object-Oriented Analysis & Design Evaluating Class Diagrams Topics include: Cohesion, Coupling Law of Demeter (handout)
Software Construction Lab 05 Abstraction, Inheritance, and Polymorphism in Java.
Chapter 10 Design Patterns.
MPCS – Advanced java Programming
CS 350 – Software Design The Strategy Pattern – Chapter 9
Composite Pattern SE2811 Software Component Design
Objects First with Java A Practical Introduction using BlueJ
CS 4240 Principles of SW Design
“The Trouble with Observer” and “Visitor Revisited”
Week 7, Class 1: The Command Pattern (cont.)
Menu item at a restaurant
DESIGN PATTERNS : Strategy Pattern
DESIGN PATTERNS : State Pattern
Design pattern Lecture 9.
Objects First with Java A Practical Introduction using BlueJ
13. Composite Pattern SE2811 Software Component Design
Objects First with Java A Practical Introduction using BlueJ
13. Composite Pattern SE2811 Software Component Design
16. Visitors SE2811 Software Component Design
16. Visitors SE2811 Software Component Design
Refactoring.
Presentation transcript:

Go4 Visitor Pattern Presented By: Matt Wilson

Introduction 2  This presentation originated out of casual talk between former WMS “C++ Book Club” (defunct program) developers who wanted to continue to get together on occasion to discuss technical topics.  It’s expected that all Senior Software Engineers understand the G04 Design Patterns well, and thus their occasional review is useful.

Introduction 3  This Presentation Series was created to not only teach what the patterns are, but explain best-practices of when and why you would want to use them  Sources used here included the Gang of 4 Design Patterns Book, Head First Design Patterns book, and many online articles and discussion boards on the topic.

Visitor Pattern 4

What-is/Why-use Visitor Pattern? 5  Formal definition: “Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.”  Or in other words: Visitor Pattern enables you to add Operations* to Classes without changing the Class’ interface.  A “Visitor” class encapsulates an Operation (“doX()”)  A Visitor can perform its operation on any object that supports being “visited”.  Support for being “visited” is added to a class by inheriting from the Visitable-Element interface.

What-is/Why-use Visitor Pattern? 6  *Operations can be thought of like Methods, but with the following difference:  Methods use Single Dispatch: Code that gets called only depends on the dynamic type of one object.  Visitor Operations use Double Dispatch: Code that gets called depends on the dynamic type of two objects, the Visitor and the object being visited.  Visitor is a useful pattern to use when you want to perform operations across a structure of objects.  Visitor is a useful pattern to use when working in Graphical GUI systems, where you don’t know what the object types are.

Visitor Pattern – UML 7

8

Visitor Pattern – example (Java) 9 //Element interface public interface Visitable { public void accept(Visitor visitor); } //concrete element public class Book implements Visitable { private double price; private double weight; //accept the visitor public void accept(Visitor vistor) { visitor.visit(this); // Second Dispatch Here } public double getPrice() { return price; } public double getWeight() { return weight; } }

Visitor Pattern – example (Java) 10 public interface Visitor { public void visit(Book book); //visit other concrete items public void visit(CD cd); public void visit(DVD dvd); } public class PostageVisitor implements Visitor { private double totalPostageForCart; //collect data about the book public void visit(Book book) { //assume we have a calculation here related to weight and price //free postage for a book over 10 if(book.getPrice() < 10.0) { totalPostageForCart += book.getWeight() * 2; } //add visitor methods for every other concrete class that the Visitor need to support public void visit(CD cd){...} public void visit(DVD dvd){...} //return the internal state public double getTotalPostage() { return totalPostageForCart; }

Visitor Pattern – example (Java) 11 // Our main program public class ShoppingCart { //normal shopping cart stuff private ArrayList items; public double calculatePostage() { //create a visitor PostageVisitor visitor = new PostageVisitor(); //iterate through all items for(Visitable item: items) { item.accept(visitor); // First Dispatch Here } double postage = visitor.getTotalPostage(); return postage; }

Visitor Pattern – Type Switching done better? 12  Other uses: Visitor Pattern can be useful for encapsulating fragile type-switching code:  Example, instead of this:  If (X is typeA) { doA } else if (X is typeB) { do B() }…  You can do this:  X.accept(visitor);  The visitor encapsulates the appropriate operations (doA, doB, etc.) based on what Type of Object X is.

Visitor Pattern – Type Switching done better? 13  Note: Switching on Type is a Code Smell that might get flagged in a Code Review. Remember that your classes shouldn’t have references to Concrete Classes to begin with, according to one of the five SOLID Principles of OO Design.  Before implementing Visitor to replace the if-else logic, the design should be examined to see if it type switching can be avoided entirely.

Visitor Pattern – If-Else 14  It was noted in the presentation on Strategy/State Patterns that they are also effective at removing if-else logic, however the differences are:  In Visitor Pattern, the removal is achieved by replacing if/else- type-switching with the Visitor’s double dispatch mechanism.  In Strategy/State Patterns, the removal is made by single dispatch via a call to the current Strategy or State, and is not based on type-switching.

Visitor Pattern Tradeoffs 15  Upsides:  A Visitor is highly cohesive, as it is only responsible to perform a single operation.  We can create as many Visitors as we want without changing underlying structure.  Downside:  Visitors are highly coupled to the elements they visit because they need to reference every type they have to visit.  If the object hierarchy it has to visit changes, then ALL visitors need to change.  Guideline: Use Visitor when the visited object hierarchy isn’t expected to be extended over time.

When to use the Visitor Pattern 16  Use the Visitor Pattern when:  You want to a dd functions to class libraries that you don’t have access to the Source Code.  You want to recover type information without doing a dynamic cast.  You want to apply an operation over a Composite Pattern, because Visitors can traverse a Composite.  You want to apply an operation to a bunch of unrelated objects, thus avoiding the need to implement Proxy Pattern.  You want to encapsulate operations into single classes, rather than change your derived classes to add these operations.

Visitor Pattern Questions ? 17