Design Patterns. Visitor Pattern. Hans Vangheluwe and Alexandre Denault

Similar documents
Visitor Pattern CS356 Object-Oriented Design and Programming November 5, 2014 Yu Sun, Ph.D.

drawobject Circle draw

Object-Oriented Oriented Programming

Chapter 4. Abstract Syntax

Project Compiler. CS031 TA Help Session November 28, 2011

Think of drawing/diagramming editors. ECE450 Software Engineering II. The problem. The Composite pattern

Design patterns (part 3)

CS 4120 Introduction to Compilers

CSE P 501 Compilers. Implementing ASTs (in Java) Hal Perkins Autumn /20/ Hal Perkins & UW CSE H-1

CSE P 501 Compilers. Implementing ASTs (in Java) Hal Perkins Winter /22/ Hal Perkins & UW CSE H-1

CSE 401/M501 Compilers

The Visitor Pattern. Object interfaces are fixed and diverse, Need to allow new operations, without coupling.

The Visitor Pattern. Design Patterns In Java Bob Tarr

The Object Recursion Pattern

CSE 331 Software Design & Implementation

Lecture 8 CS 412/413 Spring '00 -- Andrew Myers 2. Lecture 8 CS 412/413 Spring '00 -- Andrew Myers 4

Today. Assignments. Lecture Notes CPSC 326 (Spring 2019) Operator Associativity & Precedence. AST Navigation. HW4 out (due next Thurs)

Introduction to Programming Using Java (98-388)

Program Representations

CSE 12 Abstract Syntax Trees

Grammars and Parsing, second week

CSE 331 Software Design & Implementation

Semantic Analysis. Compiler Architecture

CSE 431S Type Checking. Washington University Spring 2013

Prof. Mohamed Hamada Software Engineering Lab. The University of Aizu Japan

OO Overkill When Simple is Better than Not

Computer Science II. OO Programming Classes Scott C Johnson Rochester Institute of Technology

What is a Pattern? Lecture 40: Design Patterns. Elements of Design Patterns. What are design patterns?

Java Magistère BFA

More on Inheritance. Interfaces & Abstract Classes

Type Inference Systems. Type Judgments. Deriving a Type Judgment. Deriving a Judgment. Hypothetical Type Judgments CS412/CS413

CS 231 Data Structures and Algorithms, Fall 2016

Object Oriented Programming

Design patterns (part 2) CSE 331 Spring 2010

BFH/HTA Biel/DUE/Course 355/ Software Engineering 2

CSE 331 Summer 2017 Final Exam. The exam is closed book and closed electronics. One page of notes is allowed.

Compiler Design Spring 2017

CPS2000 Compiler Theory & Practice

Dispatch techniques and closure representations

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

CMPT 379 Compilers. Parse trees

Object-oriented Compiler Construction

BEHAVIORAL DESIGN PATTERNS

Administration CS 412/413. Why build a compiler? Compilers. Architectural independence. Source-to-source translator

Compilers and computer architecture: Semantic analysis

Reflective Visitor Pattern

Grammars and Parsing for SSC1

OO Overkill When Simple is Better than Not

C++ Important Questions with Answers

This exam is open book. Each question is worth 3 points.

Introduction to Parsing. Lecture 8

CS 432 Fall Mike Lam, Professor. Code Generation

Collections, Maps and Generics

OBJECT ORIENTED PROGRAMMING

Intermediate Code Generation

Type Hierarchy. Comp-303 : Programming Techniques Lecture 9. Alexandre Denault Computer Science McGill University Winter 2004

About this exam review

Functional Design Patterns. Rumours. Agenda. Command. Solution 10/03/10. If you only remember one thing. Let it be this:

CS 553 Compiler Construction Fall 2007 Project #1 Adding floats to MiniJava Due August 31, 2005

C++ Inheritance and Encapsulation

Programming Languages & Translators PARSING. Baishakhi Ray. Fall These slides are motivated from Prof. Alex Aiken: Compilers (Stanford)

Introduction to Compiler Design

Outline. Limitations of regular languages. Introduction to Parsing. Parser overview. Context-free grammars (CFG s)

CS 406: Syntax Directed Translation

University of Cape Town ~ Department of Computer Science. Computer Science 1015F ~ 2007

UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N. Hilfinger

Acknowledgements. Materials were borrowed from

Visitors. Move functionality

TDDB84 Design Patterns Lecture 10. Prototype, Visitor

TDDB84 Design Patterns Lecture 10. Prototype, Visitor

Type Checking. Outline. General properties of type systems. Types in programming languages. Notation for type rules.

Chapter 6 Introduction to Defining Classes

Paytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value

Outline. General properties of type systems. Types in programming languages. Notation for type rules. Common type rules. Logical rules of inference

Design Patterns: State, Bridge, Visitor

Nested Classes in Java. Slides by: Alon Mishne Edited by: Eran Gilad, Eyal Moscovici April 2013

CS61B Lecture #20: Trees. Last modified: Mon Oct 8 21:21: CS61B: Lecture #20 1

CSE P 501 Exam 8/5/04

Goal of lecture. Object-oriented Programming. Context of discussion. Message of lecture

Compilers CS S-05 Semantic Analysis

Compiler Construction I

Implementing Interfaces. Marwan Burelle. July 20, 2012

Lec #6: Review, Generics and Recursion

Concepts of Object-Oriented Programming Peter Müller

Notes - Recursion. A geeky definition of recursion is as follows: Recursion see Recursion.

CS558 Programming Languages

Object-Oriented Languages and Object-Oriented Design. Ghezzi&Jazayeri: OO Languages 1

Java classes cannot extend multiple superclasses (unlike Python) but classes can implement multiple interfaces.

Generating Programs with Grammars and ASTGen

PART A : MULTIPLE CHOICE Circle the letter of the best answer (1 mark each)

A Pattern Language To Visitors

Chapter 4 :: Semantic Analysis

Compilers Project 3: Semantic Analyzer

Compiler Construction Lent Term 2015 Lectures 10, 11 (of 16)

LECTURE 3. Compiler Phases

CS2110 Assignment 3 Inheritance and Trees, Summer 2008

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

IR Optimization. May 15th, Tuesday, May 14, 13

Comp Intermediate Programming EXAM #1 February 16, 2004 Rice University - Instructors: Cox & Nguyen

9/5/17. The Design and Implementation of Programming Languages. Compilation. Interpretation. Compilation vs. Interpretation. Hybrid Implementation

Transcription:

Design Patterns Visitor Pattern Hans Vangheluwe and Alexandre Denault

3D Room

Scene Graphs Universe Room 1 Room 2 Desk Bed Wardrobe Books Lamp Doors Drawers

What if? I want to print out the content of the universe. To do this, I need to build a string containing a list of the items in the room. How do I do this? universe.tostring() (recursively)

The Challenge The class calling the universe.tostring() method should not have information on how data is stored in the universe. Thus, universe.tostring() should take care of traversing the tree. This means that each node will need to have its own tostring() method. If I want to calculate the weight of the universe, I will also need to add a getweight() function to each node. Is there a generic way I can traverse a structure (tree) without having to add new methods to the classes encoding the structure?

Visitor Pattern Put an operation to be performed on the elements of an object structure in a separate class. Separate the algorithm from the data structure.

Introduction to Compilers A compiler is a tool that transforms a program/model from a high level representation to a lower level representation. Java -> Bytecode C -> Assembler The first step of a compiler is to transform the source code into an abstract syntax tree (as specified by a language grammar ). Flex + Bison in C SableCC in Java

int i = 5; float j = 4.5; float k = i + j; The Code (input to compiler)

The constructed AST

Class Diagram of the AST

Compilers Continued Further operations are done by traversing the tree Weeding Type Checking Symbol Table Generation Code Generation Do we want to add (recursive) methods to every node we need to traverse? This would be the intuitive solution We would need the following methods: weed(), typecheck(), symbol(), code()

Naieve Solution

Problem Each node class is polluted with several methods. The implementation of an algorithm is spread over all classes. i.e. The weeding algorithm is spread across several nodes. To keep track of the traversal, either must use global variables must pass arguments by reference in each method call

Visitor Pattern Solution

Advantages The traversal algorithm is now located in a single class. All variables needed to execute the algorithm are also in the class. No need for global variables anymore (or variables passed by reference). The AST class structure (tree) was not modified! It could even be pre-compiled! It's easy to add new operations (new Visitor sub-class).

Disadvantages However, if a new subtype of Node is added, all the visitors must be modified. For instance, we might want to add an 'Addition' node. This would require a new function 'visitaddition' in each visitor. Encapsulation could be broken if a visitor needs to access an element's internal state.

Class Diagram

Sequence Diagram double dispatch

Composite Elements Data structures are often composite: a node contains references to other nodes (children, etc). For the visitor pattern to work, the accept() calls must be propagated to the children nodes (other references). Most often, the simplest solution is add this propagation to the accept() call of the parent. public void accept(visitor visitor) { visitor.visit(this); for (Node node: nodes) { node.accept(visitor)

Example

Add the visitor pattern

class Wheel { public void accept(visitor visitor) { visitor.visitwheel(this); Wheel, Body, Engine class Engine { public void accept(visitor visitor) { visitor.visitengine(this); class Body { public void accept(visitor visitor) { visitor.visitbody(this);

Car class Car { private Engine engine; private Body body; private Wheel[] wheels; public void accept(visitor visitor) { visitor.visitcar(this); engine.accept(visitor); body.accept(visitor); for(int i = 0; i < wheels.length; ++i) { wheels[i].accept(visitor);

class PrintVisitor implements Visitor { private static count = 0; Visitor public void visitwheel(wheel wheel) { count++; System.out.println("Visiting wheel " + count); public void visitengine(engine engine) { System.out.println("Visiting engine"); public void visitbody(body body) { System.out.println("Visiting body"); public void visitcar(car car) { System.out.println("Visiting car"); Caveat: multiple visits?

Composite Concerns When dealing with composites, who should take care of the traversal? The Composite An External class The Visitor

Traversal encoded in Composite Using the composite to take care of the traversal is the simplest solution. Remember the car example. public void accept(visitor visitor) { visitor.visitcar(this); engine.accept(visitor); body.accept(visitor); for(int i = 0; i < wheels.length; ++i) { wheels[i].accept(visitor); Unfortunately, this only works if all the visitors need to visit the elements in the same order.

Traversal encoded in External Class Use an external class to define the traversal. That class would require internal knowledge of the data structure, but at least the visitor would remain generic. This traversal object could even be an iterator.

Traversal encoded in External Class BreadthFirst

Traversal encoded in Visitor To allow different traversal orders (for different visitors), the traversal could be in the visitors. This would allow each visitor to use a specific traversal. This is the only solution for very complex traversal.

int i = 5; float j = 4.5; float k = i + j; Back to the AST example

AST example

Visitor class PrettyPrinterVisitor implements Visitor {... public visitstatement(statement elem) { elem.def.accept(this) elem.assign.accept(this) print( ; ); public visitassignment(assignment elem) { elem.id.accept(this) print( = ); elem.exp.accept(this)...

Drawbacks The visitor needs to know and understand the data structure. Breaks the abstraction, creates coupling Each visitor must include information on how to traverse the data structure. Can lead to lots of duplicate code.

DSheet

Dsheet: Composite Pattern ++

Dsheet: Visitor Pattern