Centralized vs. Decentralized Interpreter Pattern Visitor Pattern.

Slides:



Advertisements
Similar presentations
Framework is l Reusable Code, often domain specific (GUI, Net, Web, etc) l expressed as l a set of classes and l the way objects in those classes collaborate.
Advertisements

Intro to OOP with Java, C. Thomas Wu Inheritance and Polymorphism
Smalltalk Coding Patterns mostly from Smalltalk Best Practice Patterns Kent Beck Prentice-Hall, 1997.
Stéphane Ducasse«ChapterNr».1 Selected Design Patterns Design Patterns are recurrent solutions to design problems They are pros and cons We already saw:
Principles of Object-Oriented Software Development The language Smalltalk.
INTERPRETER Main Topics What is an Interpreter. Why should we learn about them.
Stéphane Ducasse 1 The Taste of Smalltalk.
Dynamic Object-Oriented Programming with Smalltalk 1. Introduction Prof. O. Nierstrasz Summer Semester 2006.
High-Level Programming Languages
Cse321, Programming Languages and Compilers 1 6/19/2015 Lecture #18, March 14, 2007 Syntax directed translations, Meanings of programs, Rules for writing.
Context-Free Grammars Lecture 7
Introduction to ML - Part 2 Kenny Zhu. What is next? ML has a rich set of structured values Tuples: (17, true, “stuff”) Records: {name = “george”, age.
PZ06BX Programming Language design and Implementation -4th Edition Copyright©Prentice Hall, PZ06BX - Introduction to Smalltalk Programming Language.
Visitor Pattern Jeff Schott CS590L Spring What is the Purpose of the Visitor Pattern ? n Represent an operation to be performed on the elements.
Trees. Definition of a tree A tree is like a binary tree, except that a node may have any number of children –Depending on the needs of the program, the.
Ralph Johnson - University of Illinois1 Reflection and the Adaptive Object Model Architecture Ralph Johnson University of Illinois at Urbana-Champaign.
CS 280 Data Structures Professor John Peterson. Lexer Project Questions? Must be in by Friday – solutions will be posted after class The next project.
Stéphane Ducasse 1 Objects to the Roots: Learning from beauty.
03G-1 Everything is an Object Examining builtin classes All these are classes in Little Smalltalk:  Object  Class  Method  Block  Boolean True False.
The Composite Pattern.. Composite Pattern Intent –Compose objects into tree structures to represent part-whole hierarchies. –Composite lets clients treat.
About the Presentations The presentations cover the objectives found in the opening of each chapter. All chapter objectives are listed in the beginning.
Chapter 10 Classes Continued
Object-oriented programming and design 1 Smalltalk in a Nutshell Objects & classes Messages & methods Inheritance & metaclasses.
Interpreter By: Mahmoodreza Jahanseir Amirkabir University of Technology Computer Engineering Department Fall 2010.
Stéphane Ducasse5.1 Smalltalk in a Nutshell OO Model in a Nutshell Syntax in a Nutshell.
Object Oriented Concepts. Movement toward Objects Instead of data-oriented or process-oriented Analysis, many firms are now moving to object-oriented.
Stéphane Ducasse 1 Smalltalk in a Nutshell.
S.Ducasse Stéphane Ducasse 1 The Taste of Smalltalk.
ECE450 - Software Engineering II1 ECE450 – Software Engineering II Today: Design Patterns VI Composite, Iterator, and Visitor Patterns.
1 An introduction to design patterns Based on material produced by John Vlissides and Douglas C. Schmidt.
(c) University of Washington03-1 CSC 143 Java Inheritance Reading: Ch. 10.
The Interpreter Pattern. Defining the Interpreter Intent Given a language, define a representation for its grammar along with an interpreter that uses.
2.2 A Simple Syntax-Directed Translator Syntax-Directed Translation 2.4 Parsing 2.5 A Translator for Simple Expressions 2.6 Lexical Analysis.
XP 1 CREATING AN XML DOCUMENT. XP 2 INTRODUCING XML XML stands for Extensible Markup Language. A markup language specifies the structure and content of.
Design Pattern Interpreter By Swathi Polusani. What is an Interpreter? The Interpreter pattern describes how to define a grammar for simple languages,
1 COSC3557: Object-Oriented Programming Haibin Zhu, Ph. D. Associate Professor of CS, Nipissing University.
XSLT part of XSL (Extensible Stylesheet Language) –includes also XPath and XSL Formatting Objects used to transform an XML document into: –another XML.
Object-oriented Programming and Design 1 Polymorphism Poly => many Morph => shape Variables take on many shapes, or many classes of objects.
ISBN Chapter 3 Describing Semantics -Attribute Grammars -Dynamic Semantics.
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
ECE450 - Software Engineering II1 ECE450 – Software Engineering II Today: Design Patterns IX Interpreter, Mediator, Template Method recap.
Stéphane Ducasse 1 Visitor.
Smalltalk (and Squeak) Aida Dungan and Rick Shreve.
Chapter 12 Support for Object oriented Programming.
....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.
CS 153: Concepts of Compiler Design September 16 Class Meeting Department of Computer Science San Jose State University Fall 2015 Instructor: Ron Mak
Refactoring 2. Admin Blackboard Quiz Acknowledgements Material in this presentation was drawn from Martin Fowler, Refactoring: Improving the Design of.
Observer, Strategy, Decorator, Prototype,. Observer Pattern Dependence mechanism / publish-subscribe / event handler / constraints / broadcast Let objects.
Smalltalk in a.NET World How to write a Smalltalk compiler without writing a VM John Brant
Copyright © 2003 ProsoftTraining. All rights reserved. Perl Fundamentals.
Patterns Composite Pattern. Patterns All designers use patterns. Patterns in solutions come from patterns in problems. "A pattern is a solution to a problem.
The Visitor Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
The Interpreter Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
S.Ducasse Stéphane Ducasse 1 Smalltalk in a Nutshell.
S.Ducasse Stéphane Ducasse savoie.fr e/ e/ 1 Smalltalk in a Nutshell.
Interpreter By: Mahmoodreza Jahanseir Amirkabir University of Technology Computer Engineering Department Fall 2010.
Stéphane Ducasse 1 Abstract Classes.
Patterns Protect from Change Rule: if something is going to change, make it an object. Strategy: make algorithm an object so it can change State: make.
Sections Inheritance and Abstract Classes
A Simple Syntax-Directed Translator
CS510 Compiler Lecture 4.
Introduction to Parsing (adapted from CS 164 at Berkeley)
Behavioral Design Patterns
Types of Programming Languages
Presentation by Julie Betlach 7/02/2009
Interpreter Pattern.
Introduction to Smalltalk
CSE 3302 Programming Languages
Trees That Represent Grammars
Presentation transcript:

Centralized vs. Decentralized Interpreter Pattern Visitor Pattern

Defining a picture TextFig. Drawing CompFig. CompFig. RectangleFig. TextFig. RectangleFig.

Defining a Language for Pictures Figure - displayOn: is abstract method CompositeFigure Drawing RectangleFigure TextFigure

Interpreter Pattern Tree of objects is a kind of program Interpret program by sending message to root, which is recursively sent to entire tree. Not about parsing!!!

Object-Oriented Interpreters To write a little object-oriented interpreter for a language L: 1) make a subclass of LParseNode for each rule in the grammar of L 2) for each subclass, define an interpreter method that takes the current context as an argument.

Object-Oriented Interpreters 3) define protocol for making a tree of LParseNodes. 4) define a program for L by building an abstract syntax tree.

Example: ValueModels ValueModel value ValueHolder value value BlockValue block arguments value

ValueModels | x y | x := 3 asValue. y := 7 asValue. x + y ValueModel>> + aValue ^ BlockValue block: [:a :b | a value * b value] arguments: (Array with: self with: aValue asValue) ValueHolder BlockValue ValueHolder

Example: Regular Expression Checker Grammar: exp ::= string | exp ‘+’ exp | exp ‘&’ exp | exp ‘repeat’ Step 1: define RegExpNode, MatchRENode, AlternationRENode, SequenceRENode, RepeatRENode Step 2: define a match: method for each class that takes an input state as an argument

Regular Expression Classes RegExpNode SequenceRENode Match Match MatchRENode contents Match RepeatRENode Match AlternationRENode Match

Regular Expression Objects 'this is a ' ('very ' *) ('big ’ + 'small ') ('dog' + 'cat' + 'mouse') SequenceRENode MatchRENode 'this is a ' RepeatRENode MatchRENode 'big ' AlternationRENode AlternationRENode MatchRENode 'small ' MatchRENode 'very ' MatchRENode'dog' MatchRENode'mouse MatchRENode'cat' this is a very very very big mouse

Matching SequenceRENode>>match: inputState ^components inject: inputState into: [:nextState :exp | exp match: nextState]

Matching RepeatRENode>>match: inputState | aState finalState | aState := inputState. finalState := inputState copy....

(continued) [aState notEmpty] whileTrue: [aState := component match: aState. finalState addAll: aState]. ^finalState

Matching AlternationRENode>>match: inputState | finalState | finalState := REState new. components do: [ :exp | finalState addAll: (exp match: inputState)] ^finalState

Matching MatchRENode>>match: inputState | finalState tStream | finalState := REState new.... REState is a collection of streams.

(continued) inputState do: [:stream | tStream := stream copy. (tStream nextAvailable: components size) = components ifTrue: [finalState add: tStream]]. ^finalState

Protocol for Building Tree Define ”+" and "repeat" and ”&" as methods on RegExpNodes and any literals that are to be treated as patterns, such as strings. Then (('dog ' + 'cat ') repeat & 'weather') matches: 'dog dog cat weather' is true.

Interface method RegExpNode>>matches: anArg | inputState | inputState := (streamOrCollection isKindOf: Collection) ifTrue: [REState with: (ReadStream on: streamOrCollection)] ifFalse: [REState with: streamOrCollection]. (self match: inputState) do: [:stream | stream atEnd ifTrue: [^true]]. ^false

Interface methods Define +, &, repeat, and asRENode in RegExpNode and String + anArg ^AlternationRENode new components: (Array with: self with: anArg asRENode)

Other examples of Interpreter pattern: producing Postscript for a document figuring out the value of an insurance policy spreadsheet compiling a program C program would use case statement

Replacing Cases with Subclasses Advantages instead of modifying case statements, add a new subclass easier to parameterize can use inheritance to make new options

Replacing Cases with Subclasses Disadvantages program is spread out, + harder to understand + harder to replace algorithm state of object can change, but class can not

How To Centralize Algorithms Define isAlternative, isRepeat, isSequence, isMatch, childrenDo: fix: anRENode anRENode isMatch ifTrue: [anRENode contents: (anRENode contents capitalize)] ifFalse: [anRENode childrenDo: [:child | self fix: child]]

When to Centralize Algorithm Use centralized algorithm when you need to change entire algorithm at once look at entire algorithm at once change algorithm, but not add new classes of components

Visitor pattern Visitor lets you centralize algorithm, lets you create a family of algorithms by inheritance, and makes it easy to create new algorithms. Major problem is that adding a new kind of parse node requires adding a new method to each visitor.

Visitor pattern two kinds of classes: nodes and node visitor nodes have accept: method with visitor as an argument accept: method sends visit message SequenceRENode>>accept: aVisitor aVisitor visitSequence: self

Visitor pattern each node class sends a different visit message to visitor visitSequence:, visitAlternation:, visitRepetition:, visitMatch: visitor defines a visit method for each class of parse tree node uses double dispatching

REVisitor and MatchVisitor An REVisitor implements visitSequence:, visitAlternation:, visitRepetition:, visitMatch: MatchVisitor is an REVisitor with one instance variable, state, and methods to access it.

MatchVisitor>>visitSequence: sequence ^state := sequence components inject: state into: [:nextState :exp | visitor := MatchVisitor with: nextState. exp match: visitor. visitor state]

MatchVisitor>>visitAlternation: aNode | initialState finalState | initialState := state. finalState := REState new. components do: [ :eachComponent | state := initialState. eachComponent accept: self. finalState addAll: state] state := finalState

MatchVisitor>>visitRepeat: aNode | finalState | finalState := state copy. [state notEmpty] whileTrue: [component accept: self. finalState addAll: state]. ^finalState

FixVisitor FixVisitor>>visitMatch: aMatch aMatch contents: (aMatch contents capitalize) FixVisitor>>visitSequence: aSequence aSequence childrenDo: [:child | child accept: self]]

Visitor as a refactoring Convert an “interpret:” method to Visitor. Precondition: interpret: must not return anything. Create a visitor class V. Find common superclass of the classes that define interpret:, and define interpret: aContext self accept: (V newWith: aContext)

Visitor as a refactoring Add an accept: method to every class X with interpret:, and have it send visitX: to argument. Move code for interpret: in class X to visitX: of V. Add accessing methods to X. Change sends of interpret: to accept:

Comments Design pattern is a complex refactoring Visitor illustrates that location of code is arbitrary

Visitor Pattern Strengths Can add a new algorithm to operate on a class hierarchy without changing existing classes. Weakness Adding a new node class requires changing visitors.

ParseTreeEnumerator Smalltalk compiler parse tree hierachy rarely changes. Many programs need to traverse tree: consistency checkers program transformation metrics Keep them out of the parse tree.

VisualWorks GUI Specs A tree of Specs describes the components of a window. You build a window for an application by asking the Spec for that window to do it. UIPolicy is a Visitor that converts a tree of Specs into a tree of VisualComponents.

dispatchTo: policy with: builder ActionButtonSpec policy actionButton: self into: builder CompositeSpec policy composite: self into: builder

Summary Two related patterns: Interpreter - distribute code over class hierarchy Visitor - centralize code in single class