en wikipedia org wiki visitor pattern java example
TRANSCRIPT
-
8/13/2019 En Wikipedia Org Wiki Visitor Pattern Java Example
1/15
pdfcrowd comopen in browser PRO version Are you a developer? Try out the HTML to PDF API
Visitor pattern
Visitor in UML
From Wikipedia, the free encyclopedia
In object-oriented programmingand software engineering, the visitor
design patternis a way of separating an algorithmfrom an object
structure onwhich it operates. A practical result of this separation is
the ability to add new operations to exist ing object structureswithout
modifying those structures. It is one way to follow the open/closed
principle.
In essence, the visitor allows one to add new virtual functionsto 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. The visitor takes the instance
reference as input, and implements the goal through double dispatch.
Contents [hide]
1 Motivation
2 Details
3 Java example
3.1 Diagram
Article Talk Read Edit View history Search
Main page
Contents
Featured content
Current events
Random article
Donate to Wikipedia
Interaction
Help
About Wikipedia
Comm unity portal
Recent changes
Contact page
Tools
Print/export
Languages
Create account Log in
http://en.wikipedia.org/wiki/File:VisitorClassDiagram.svghttp://en.wikipedia.org/wiki/File:VisitorClassDiagram.svghttp://en.wikipedia.org/wiki/File:VisitorClassDiagram.svghttp://en.wikipedia.org/wiki/Double_dispatchhttp://en.wikipedia.org/wiki/Double_dispatchhttp://en.wikipedia.org/wiki/File:VisitorClassDiagram.svghttp://en.wikipedia.org/wiki/File:VisitorClassDiagram.svghttp://en.wikipedia.org/wiki/Virtual_functionhttp://en.wikipedia.org/wiki/File:VisitorClassDiagram.svghttp://en.wikipedia.org/wiki/Open/closed_principlehttp://en.wikipedia.org/wiki/File:VisitorClassDiagram.svghttp://en.wikipedia.org/wiki/Open/closed_principlehttp://en.wikipedia.org/wiki/File:VisitorClassDiagram.svghttp://en.wikipedia.org/wiki/File:VisitorClassDiagram.svghttp://en.wikipedia.org/wiki/File:VisitorClassDiagram.svghttp://en.wikipedia.org/wiki/Software_design_patternhttp://en.wikipedia.org/wiki/Wikipedia:Contact_ushttp://en.wikipedia.org/wiki/Special:RecentChangeshttp://en.wikipedia.org/wiki/Help:Contentshttps://donate.wikimedia.org/wiki/Special:FundraiserRedirector?utm_source=donate&utm_medium=sidebar&utm_campaign=C13_en.wikipedia.org&uselang=enhttp://en.wikipedia.org/wiki/Special:Randomhttp://en.wikipedia.org/wiki/Portal:Current_eventshttp://en.wikipedia.org/wiki/Main_Pagehttp://en.wikipedia.org/wiki/Main_Pagehttp://en.wikipedia.org/wiki/Main_Pagehttp://pdfcrowd.com/http://pdfcrowd.com/redirect/?url=http%3a%2f%2fen.wikipedia.org%2fwiki%2fVisitor_pattern%23Java_example&id=ma-131216214619-60becd27http://pdfcrowd.com/customize/http://pdfcrowd.com/html-to-pdf-api/?ref=pdfhttp://en.wikipedia.org/wiki/File:VisitorClassDiagram.svghttp://en.wikipedia.org/wiki/File:VisitorClassDiagram.svghttp://en.wikipedia.org/wiki/Unified_Modeling_Languagehttp://en.wikipedia.org/wiki/Object-oriented_programminghttp://en.wikipedia.org/wiki/Software_engineeringhttp://en.wikipedia.org/wiki/Software_design_patternhttp://en.wikipedia.org/wiki/Algorithmhttp://en.wikipedia.org/wiki/Open/closed_principlehttp://en.wikipedia.org/wiki/Virtual_functionhttp://en.wikipedia.org/wiki/Double_dispatchhttp://en.wikipedia.org/wiki/Visitor_patternhttp://en.wikipedia.org/wiki/Talk:Visitor_patternhttp://en.wikipedia.org/wiki/Visitor_patternhttp://en.wikipedia.org/w/index.php?title=Visitor_pattern&action=edithttp://en.wikipedia.org/w/index.php?title=Visitor_pattern&action=historyhttp://en.wikipedia.org/wiki/Main_Pagehttp://en.wikipedia.org/wiki/Portal:Contentshttp://en.wikipedia.org/wiki/Portal:Featured_contenthttp://en.wikipedia.org/wiki/Portal:Current_eventshttp://en.wikipedia.org/wiki/Special:Randomhttps://donate.wikimedia.org/wiki/Special:FundraiserRedirector?utm_source=donate&utm_medium=sidebar&utm_campaign=C13_en.wikipedia.org&uselang=enhttp://en.wikipedia.org/wiki/Help:Contentshttp://en.wikipedia.org/wiki/Wikipedia:Abouthttp://en.wikipedia.org/wiki/Wikipedia:Community_portalhttp://en.wikipedia.org/wiki/Special:RecentChangeshttp://en.wikipedia.org/wiki/Wikipedia:Contact_ushttp://en.wikipedia.org/wiki/Main_Pagehttp://en.wikipedia.org/w/index.php?title=Special:UserLogin&returnto=Visitor+pattern&type=signuphttp://en.wikipedia.org/w/index.php?title=Special:UserLogin&returnto=Visitor+pattern -
8/13/2019 En Wikipedia Org Wiki Visitor Pattern Java Example
2/15
pdfcrowd comopen in browser PRO version Are you a developer? Try out the HTML to PDF API
Visitor in LePUS3(legend )
3.2 Sources
3.3 Output
4 Lisp Example
4.1 Sources
4.2 Output
4.3 Notes
5 Scala Example
5.1 Sources
5.2 Output5.3 Notes
6 Output
7 State
8 Related des ign patterns
9 See also
10 References
11 External links
Motivation [edit]
Consider the design of a 2D CAD system. At its core there are several types to represent basic geometric shapes like circles,
lines and arcs. The entities are ordered into layers, and at the top of the type hierarchy is the drawing, which is simply a list of
layers, plus some additional properties.
A fundamental operation on this type hierarchy is saving the drawing to the system's native file format. At first glance it may
seem acceptable to add local save methods to all types in the hierarchy. But then we also want to be able to save drawings
to other file formats, and adding more and more methods for saving into lots of different file formats soon clutters the relatively
pure geometric data s tructure we started out with.
A naive way to solve this would be to maintain separate functions for each file format. Such a save function would take a
drawing as input, traverse it and encode into that specific file format. But if you do this for several different formats, you soon
begin to see lots of duplication between the functions, e.g. lots of type-of if statements and traversal loops. Another problem
with this approach is how easy it is to miss a certain shape in some saver.
Instead, you could apply the Visitor pattern. The Visitor pattern encodes a logical operation on the whole hierarchy into a
single class containing one method per type. In our CAD example, each save function would be implemented as a separate
Visitor subclass. This would remove all duplication of type checks and traversal steps. It would also make the compiler
etina
Deutsch
Espaol
Franais
Galego
Italiano
Polski
Portugus
Svenska
Ting Vit
Edit links
http://fr.wikipedia.org/wiki/Visiteur_(patron_de_conception)http://cs.wikipedia.org/wiki/Visitor_(n%C3%A1vrhov%C3%BD_vzor)http://bg.wikipedia.org/wiki/%D0%9F%D0%BE%D1%81%D0%B5%D1%82%D0%B8%D1%82%D0%B5%D0%BB_(%D1%88%D0%B0%D0%B1%D0%BB%D0%BE%D0%BD)http://pdfcrowd.com/http://pdfcrowd.com/redirect/?url=http%3a%2f%2fen.wikipedia.org%2fwiki%2fVisitor_pattern%23Java_example&id=ma-131216214619-60becd27http://pdfcrowd.com/customize/http://pdfcrowd.com/html-to-pdf-api/?ref=pdfhttp://en.wikipedia.org/wiki/File:Visitor_pattern_in_LePUS3.gifhttp://en.wikipedia.org/wiki/File:Visitor_pattern_in_LePUS3.gifhttp://en.wikipedia.org/wiki/Lepus3http://lepus.org.uk/ref/legend/legend.xmlhttp://en.wikipedia.org/w/index.php?title=Visitor_pattern&action=edit§ion=1http://en.wikipedia.org/wiki/Computer-aided_designhttp://bg.wikipedia.org/wiki/%D0%9F%D0%BE%D1%81%D0%B5%D1%82%D0%B8%D1%82%D0%B5%D0%BB_(%D1%88%D0%B0%D0%B1%D0%BB%D0%BE%D0%BD)http://cs.wikipedia.org/wiki/Visitor_(n%C3%A1vrhov%C3%BD_vzor)http://de.wikipedia.org/wiki/Besucher_(Entwurfsmuster)http://es.wikipedia.org/wiki/Visitor_(patr%C3%B3n_de_dise%C3%B1o)http://fr.wikipedia.org/wiki/Visiteur_(patron_de_conception)http://gl.wikipedia.org/wiki/Visitor_(patr%C3%B3n_de_dese%C3%B1o)http://ko.wikipedia.org/wiki/%EB%B9%84%EC%A7%80%ED%84%B0_%ED%8C%A8%ED%84%B4http://it.wikipedia.org/wiki/Visitorhttp://ja.wikipedia.org/wiki/Visitor_%E3%83%91%E3%82%BF%E3%83%BC%E3%83%B3http://pl.wikipedia.org/wiki/Odwiedzaj%C4%85cyhttp://pt.wikipedia.org/wiki/Visitor_Patternhttp://ru.wikipedia.org/wiki/%D0%9F%D0%BE%D1%81%D0%B5%D1%82%D0%B8%D1%82%D0%B5%D0%BB%D1%8C_(%D1%88%D0%B0%D0%B1%D0%BB%D0%BE%D0%BD_%D0%BF%D1%80%D0%BE%D0%B5%D0%BA%D1%82%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D1%8F)http://sv.wikipedia.org/wiki/Bes%C3%B6karehttp://uk.wikipedia.org/wiki/%D0%92%D1%96%D0%B4%D0%B2%D1%96%D0%B4%D1%83%D0%B2%D0%B0%D1%87_(%D1%88%D0%B0%D0%B1%D0%BB%D0%BE%D0%BD_%D0%BF%D1%80%D0%BE%D0%B5%D0%BA%D1%82%D1%83%D0%B2%D0%B0%D0%BD%D0%BD%D1%8F)http://vi.wikipedia.org/wiki/Visitor_patternhttp://zh.wikipedia.org/wiki/%E8%AE%BF%E9%97%AE%E8%80%85%E6%A8%A1%E5%BC%8Fhttp://www.wikidata.org/wiki/Q830719#sitelinks-wikipedia -
8/13/2019 En Wikipedia Org Wiki Visitor Pattern Java Example
3/15
pdfcrowd comopen in browser PRO version Are you a developer? Try out the HTML to PDF API
complain if a shape is omitted.
Another motivation is to reuse iteration code. For example iterating over a directory structure could be implemented with a
visitor pattern. This would allow you to create file searches, file backups, directory removal, etc. by implementing a visitor for
each function while reusing the iteration code.
Details [edit]
The visitor pattern requires a programming language that supports single dispatchand method overloading. Under these
conditions, consider two objects, each of some class type; one is called the "element", and the other is called the "visitor".An element has an accept()method that can take the visitor as an argument. The accept()method calls a visit()
method of the visitor; the element passes itself as an argument to the visit()method. Thus:
When the accept()method is called in the program, its implementation is chosen based on both:
The dynamic type of the element.
The static type of the visitor.
When the associated visit()method is called, its implementation is chosen based on both:
The dynamic type of the visitor.
The static type of the element as known from within the implementation of the accept()method, which is the same
as the dynamic type of the element. (As a bonus, if the visitor can't handle an argument of the given element's type,
then the compiler will catch the error.)
Consequently, the implementation of the visit()method is chosen based on both:
The dynamic type of the element.
The dynamic type of the visitor.
This effectively implements double dispatch; indeed, because the Lisplanguage's object system supports multiple
dispatch (not just single dispatch), implementing the visitor pattern in Lisp is trivial.
In this way, a single algorithm can be written for traversing a graph of elements, and many different kinds of operations can be
performed during that traversal by supplying different kinds of visitors to interact with the elements based on the dynamic
types of both the elements and the visitors.
Java example [edit]
The following example is in the Java programming language, and shows how the contents of a tree of nodes (in this case
describing the components of a car) can be printed. Instead of creating "print" methods for each subclass (Wheel, Engine,
Body, and Car), a single class (CarElementPrintVisitor) performs the required printing action. Because different subclasses
http://pdfcrowd.com/http://pdfcrowd.com/redirect/?url=http%3a%2f%2fen.wikipedia.org%2fwiki%2fVisitor_pattern%23Java_example&id=ma-131216214619-60becd27http://pdfcrowd.com/customize/http://pdfcrowd.com/html-to-pdf-api/?ref=pdfhttp://en.wikipedia.org/w/index.php?title=Visitor_pattern&action=edit§ion=2http://en.wikipedia.org/w/index.php?title=Visitor_pattern&action=edit§ion=3http://en.wikipedia.org/wiki/Single_dispatchhttp://en.wikipedia.org/wiki/Method_overloadinghttp://en.wikipedia.org/wiki/Double_dispatchhttp://en.wikipedia.org/wiki/Lisp_(programming_language)http://en.wikipedia.org/wiki/Java_programming_language -
8/13/2019 En Wikipedia Org Wiki Visitor Pattern Java Example
4/15
pdfcrowd comopen in browser PRO version Are you a developer? Try out the HTML to PDF API
require slightly different actions to print properly, CarElementDoVisitor dispatches act ions based on the c lass of the argument
passed to it.
Diagram [edit]
Sources [edit]
interfaceICarElementVisitor { voidvisit(Wheel wheel); voidvisit(Engine engine); voidvisit(Body body); voidvisit(Car car);}
http://pdfcrowd.com/http://pdfcrowd.com/redirect/?url=http%3a%2f%2fen.wikipedia.org%2fwiki%2fVisitor_pattern%23Java_example&id=ma-131216214619-60becd27http://pdfcrowd.com/customize/http://pdfcrowd.com/html-to-pdf-api/?ref=pdfhttp://en.wikipedia.org/w/index.php?title=Visitor_pattern&action=edit§ion=4http://en.wikipedia.org/w/index.php?title=Visitor_pattern&action=edit§ion=5http://en.wikipedia.org/wiki/File:VisitorPatternUML.png -
8/13/2019 En Wikipedia Org Wiki Visitor Pattern Java Example
5/15
pdfcrowd comopen in browser PRO version Are you a developer? Try out the HTML to PDF API
interfaceICarElement { voidaccept(ICarElementVisitor visitor);// CarElements have to provide accept().}classWheel implementsICarElement { privateStringname;
publicWheel(Stringname){ this.name=name;
}
publicStringgetName(){ returnthis.name; }
publicvoidaccept(ICarElementVisitor visitor){ /* * accept(ICarElementVisitor) in Wheel implements * accept(ICarElementVisitor) in ICarElement, so the call * to accept is bound at run time. This can be considered
* the first dispatch. However, the decision to call * visit(Wheel) (as opposed to visit(Engine) etc.) can be * made during compile time since 'this' is known at compile * time to be a Wheel. Moreover, each implementation of * ICarElementVisitor implements the visit(Wheel), which is * another decision that is made at run time. This can be * considered the second dispatch. */
visitor.visit(this); }}
classEngine implementsICarElement { publicvoidaccept(ICarElementVisitor visitor){ visitor.visit(this); }}classBody implementsICarElement { publicvoidaccept(ICarElementVisitor visitor){ visitor.visit(this); }
http://pdfcrowd.com/http://pdfcrowd.com/redirect/?url=http%3a%2f%2fen.wikipedia.org%2fwiki%2fVisitor_pattern%23Java_example&id=ma-131216214619-60becd27http://pdfcrowd.com/customize/http://pdfcrowd.com/html-to-pdf-api/?ref=pdf -
8/13/2019 En Wikipedia Org Wiki Visitor Pattern Java Example
6/15
pdfcrowd comopen in browser PRO version Are you a developer? Try out the HTML to PDF API
}classCar implementsICarElement { ICarElement[]elements;
publicCar(){ //create new Array of elements this.elements=newICarElement[]{newWheel("front left"),
newWheel("front right"), newWheel("back left"),newWheel("back right"), newBody(), newEngine()};
}
publicvoidaccept(ICarElementVisitor visitor){for(ICarElement elem :elements){
elem.accept(visitor); } visitor.visit(this);
}}classCarElementPrintVisitor implementsICarElementVisitor {
publicvoidvisit(Wheel wheel){System.out.println("Visiting "+wheel.getName()+" wheel"); }
publicvoidvisit(Engine engine){ System.out.println("Visiting engine"); }
publicvoidvisit(Body body){ System.out.println("Visiting body"); }
publicvoidvisit(Car car){System.out.println("Visiting car");
}}classCarElementDoVisitor implementsICarElementVisitor { publicvoidvisit(Wheel wheel){ System.out.println("Kicking my "+wheel.getName()+" wheel"); }
http://pdfcrowd.com/http://pdfcrowd.com/redirect/?url=http%3a%2f%2fen.wikipedia.org%2fwiki%2fVisitor_pattern%23Java_example&id=ma-131216214619-60becd27http://pdfcrowd.com/customize/http://pdfcrowd.com/html-to-pdf-api/?ref=pdf -
8/13/2019 En Wikipedia Org Wiki Visitor Pattern Java Example
7/15
pdfcrowd comopen in browser PRO version Are you a developer? Try out the HTML to PDF API
publicvoidvisit(Engine engine){ System.out.println("Starting my engine"); }
publicvoidvisit(Body body){ System.out.println("Moving my body"); }
publicvoidvisit(Car car){ System.out.println("Starting my car");
}}publicclassVisitorDemo { publicstaticvoidmain(String[]args){ ICarElement car =newCar(); car.accept(newCarElementPrintVisitor()); car.accept(newCarElementDoVisitor()); }}
Note: A more flexible approach to this pattern is to create a wrapper class implementing the interface defining the acceptmethod. The wrapper contains a reference pointing to the ICarElement which could be initialized through the constructor. This
approach avoids having to implement an interface on each element. [see article Java Tip 98 article below]
Output [edit]
Visiting front left wheel
Visiting front right wheel
Visiting back left wheel
Visiting back right wheel
Visiting body
Visiting engine
Visiting car
Kicking my front left wheel
Kicking my front right wheel
Kicking my back left wheel
Kicking my back right wheel
Moving my body
Starting my engine
http://pdfcrowd.com/http://pdfcrowd.com/redirect/?url=http%3a%2f%2fen.wikipedia.org%2fwiki%2fVisitor_pattern%23Java_example&id=ma-131216214619-60becd27http://pdfcrowd.com/customize/http://pdfcrowd.com/html-to-pdf-api/?ref=pdfhttp://en.wikipedia.org/w/index.php?title=Visitor_pattern&action=edit§ion=6 -
8/13/2019 En Wikipedia Org Wiki Visitor Pattern Java Example
8/15
pdfcrowd comopen in browser PRO version Are you a developer? Try out the HTML to PDF API
Starting my car
Lisp Example [edit]
Sources [edit]
(defclass auto ()
((elements :initarg:elements)))(defclass auto-part () ((name:initarg:name:initform"")))(defmethod print-object ((p auto-part)stream) (print-object (slot-valuep 'name)stream))(defclass wheel (auto-part)())(defclass body (auto-part)())(defclass engine (auto-part)())(defgeneric traverse (functionobject other-object))(defmethod traverse (function(a auto)other-object) (with-slots (elements)a (dolist(e elements) (funcallfunctione other-object))));; do-something visitations
;; catch all(defmethod do-something (object other-object) (format t "don't know how ~s and ~s should interact~%"object other-object));; visitation involving wheel and integer(defmethod do-something ((object wheel)(other-object integer)) (format t "kicking wheel ~s ~s times~%"object other-object));; visitation involving wheel and symbol(defmethod do-something ((object wheel)(other-object symbol)) (format t "kicking wheel ~s symbolically using symbol ~s~%"object other-object))
http://pdfcrowd.com/http://pdfcrowd.com/redirect/?url=http%3a%2f%2fen.wikipedia.org%2fwiki%2fVisitor_pattern%23Java_example&id=ma-131216214619-60becd27http://pdfcrowd.com/customize/http://pdfcrowd.com/html-to-pdf-api/?ref=pdfhttp://en.wikipedia.org/w/index.php?title=Visitor_pattern&action=edit§ion=7http://en.wikipedia.org/w/index.php?title=Visitor_pattern&action=edit§ion=8 -
8/13/2019 En Wikipedia Org Wiki Visitor Pattern Java Example
9/15
df d mi b PRO i Are you a developer? Try out the HTML to PDF API
(defmethod do-something ((object engine)(other-object integer)) (format t "starting engine ~s ~s times~%"object other-object))(defmethod do-something ((object engine)(other-object symbol)) (format t "starting engine ~s symbolically using symbol ~s~%"object other-object))(let((a (make-instance 'auto :elements`(,(make-instance 'wheel :name"front-left-wheel") ,(make-instance 'wheel :name"front-right-wheel")
,(make-instance 'wheel :name"rear-right-wheel") ,(make-instance 'wheel :name"rear-right-wheel") ,(make-instance 'body :name"body") ,(make-instance 'engine :name"engine"))))) ;; traverse to print elements ;; stream *standard-output* plays the role of other-object here (traverse #'printa *standard-output*)
(terpri);; print newline
;; traverse with arbitrary context from other object
(traverse #'do-something a 42);; traverse with arbitrary context from other object
(traverse #'do-something a 'abc))
Output [edit]
"front-left-wheel"
"front-right-wheel"
"rear-right-wheel"
"rear-right-wheel""body"
"engine"
kicking wheel "front-left-wheel" 42 times
kicking wheel "front-right-wheel" 42 times
kicking wheel "rear-right-wheel" 42 times
kicking wheel "rear-right-wheel" 42 times
don't know how "body" and 42 should interact
starting engine "engine" 42 times
kicking wheel "front-left-wheel" symbolically using symbol ABC
http://pdfcrowd.com/http://pdfcrowd.com/redirect/?url=http%3a%2f%2fen.wikipedia.org%2fwiki%2fVisitor_pattern%23Java_example&id=ma-131216214619-60becd27http://pdfcrowd.com/customize/http://pdfcrowd.com/html-to-pdf-api/?ref=pdfhttp://en.wikipedia.org/w/index.php?title=Visitor_pattern&action=edit§ion=9 -
8/13/2019 En Wikipedia Org Wiki Visitor Pattern Java Example
10/15
df di b PRO i Are you a developer? Try out the HTML to PDF API
kicking wheel "front-right-wheel" symbolically using symbol ABC
kicking wheel "rear-right-wheel" symbolically using symbol ABC
kicking wheel "rear-right-wheel" symbolically using symbol ABC
don't know how "body" and ABC should interact
starting engine "engine" symbolically using symbol ABC
Notes [edit]
The other-objectparameter is superfluous in traverse. The reason is that it is possible to use an anonymous function
which calls the desired target method with a lexically captured object:
(defmethod traverse (function(a auto));; other-object removed (with-slots (elements)a (dolist(e elements) (funcallfunctione))));; from here too;; ...
;; alternative way to print-traverse
(traverse (lambda(o)(printo *standard-output*))a);; alternative way to do-something with
;; elements of a and integer 42 (traverse (lambda(o)(do-something o 42))a)
Now, the multiple dispatch occurs in the call issued from the body of the anonymous function, and so traverseis just a
mapping function which distributes a function application over the elements of an object. Thus all traces of the Visitor Pattern
disappear, except for the mapping function, in which there is no evidence of two objects being involved. All knowledge of there
being two objects and a dispatch on their types is in the lambda function.
Scala Example [edit]
Sources [edit]
classDate(valday:Int, valmonth:Int, valyear:Int)abstractclassCarElement { varlastServiced =newDate(0, 0, 0)
http://pdfcrowd.com/http://pdfcrowd.com/redirect/?url=http%3a%2f%2fen.wikipedia.org%2fwiki%2fVisitor_pattern%23Java_example&id=ma-131216214619-60becd27http://pdfcrowd.com/customize/http://pdfcrowd.com/html-to-pdf-api/?ref=pdfhttp://en.wikipedia.org/w/index.php?title=Visitor_pattern&action=edit§ion=10http://en.wikipedia.org/w/index.php?title=Visitor_pattern&action=edit§ion=11http://en.wikipedia.org/w/index.php?title=Visitor_pattern&action=edit§ion=12 -
8/13/2019 En Wikipedia Org Wiki Visitor Pattern Java Example
11/15
df di b PRO i A d l ? T t th HTML t PDF API
}classWheel(valname:String)extendsCarElement {}classBody extendsCarElement {}classEngine extendsCarElement {}classCar extendsCarElement { valelements:List[CarElement]=List(newWheel("front left"), newWheel("front right"), newWheel("back left"), newWheel("back right"), newBody(), newEngine())
}objectCarPartProcessors { defprintCarElement(element:CarElement):Unit ={ element match{ casewheel:Wheel =>println("Visiting "+ wheel.name + " wheel") caseengine:Engine =>println("Visiting engine") casebody:Body =>println("Visiting body") casecar:Car =>{ car.elements.map(printCarElement) println("Visting car") } caseother =>println("Visting unknown CarElement "+ other) } } definteractWithCarElement(element:CarElement):Unit ={ element match{ casewheel:Wheel =>println("Kicking my "+ wheel.name + " wheel") caseengine:Engine =>println("Starting my engine") casebody:Body =>println("Moving my body") casecar:Car =>{ car.elements.map(interactWithCarElement) println("Starting my car")
} caseother =>println("Unknown CarElement "+ other + " no interaction defined") } }}objectexample extendsApp { valcar =newCar() CarPartProcessors.printCarElement(car) CarPartProcessors.interactWithCarElement(car)
http://pdfcrowd.com/http://pdfcrowd.com/redirect/?url=http%3a%2f%2fen.wikipedia.org%2fwiki%2fVisitor_pattern%23Java_example&id=ma-131216214619-60becd27http://pdfcrowd.com/customize/http://pdfcrowd.com/html-to-pdf-api/?ref=pdf -
8/13/2019 En Wikipedia Org Wiki Visitor Pattern Java Example
12/15df di b PRO i A d l ? T t th HTML t PDF API
}
Output [edit]
Visiting front left wheel
Visiting front right wheel
Visiting back left wheel
Visiting back right wheel
Visiting bodyVisiting engine
Visiting car
Kicking my front left wheel
Kicking my front right wheel
Kicking my back left wheel
Kicking my back right wheel
Moving my body
Starting my engine
Starting my car
Notes [edit]
The Scala implementation has neither the notion of a visitor interface nor a visitable interface.
Now, suppose we add the following class definition:
classTransmission(valkind:String)extendsCarElement { overridedeftoString ={kind + " Transmission"}}
and change the definition of the Car class to:
classCar extendsCarElement { valelements:List[CarElement]=List(newWheel("front left"), newWheel("front right"), newWheel("back left"), newWheel("back right"), newBody(), newEngine(), newTransmission("Manual"))}
Upon rerunning the program, we get:
http://pdfcrowd.com/http://pdfcrowd.com/redirect/?url=http%3a%2f%2fen.wikipedia.org%2fwiki%2fVisitor_pattern%23Java_example&id=ma-131216214619-60becd27http://pdfcrowd.com/customize/http://pdfcrowd.com/html-to-pdf-api/?ref=pdfhttp://en.wikipedia.org/w/index.php?title=Visitor_pattern&action=edit§ion=13http://en.wikipedia.org/w/index.php?title=Visitor_pattern&action=edit§ion=14 -
8/13/2019 En Wikipedia Org Wiki Visitor Pattern Java Example
13/15df di b PRO i
Are you a developer? Try out the HTML to PDF API
Output [edit]
Visiting front left wheel
Visiting front right wheel
Visiting back left wheel
Visiting back right wheel
Visiting body
Visiting engine
Visting unknown CarElement Manual Transmission
Visting car
Kicking my front left wheel
Kicking my front right wheel
Kicking my back left wheel
Kicking my back right wheel
Moving my body
Starting my engine
Unknown CarElement Manual Transmission no interaction defined
Starting my car
State [edit]
This section does not citeany references or sources. Please help improve this
section by adding citations to reliable sources. Unsourced material may be
challenged and removed. (January 2011)
Aside from potentially improving separation of concerns, the visitor pattern has an additional advantage over simply calling a
polymorphic method: a visitor object can have state. This is extremely useful in many cases where the act ion performed on
the object depends on previous such actions.
An example of this is a pretty-printerin a programming languageimplementation (such as a compileror interpreter). Such a
pretty-printer object (implemented as a visitor, in this example), will visit nodes in a data structure that represents a parsed
and processed program. The pretty-printer will then generate a textual representation of the program tree. To make the
representation human-readable, the pretty-printer should properly indent program statements and expressions. The current
indentation levelcan then be tracked by the visitor as its state, correctly applying encapsulation, whereas in a simple
polymorphic method invocation, the indentation level would have to be exposed as a parameter and the caller would rely on
the method implementation to use and propagate this parameter correctly.
http://pdfcrowd.com/http://pdfcrowd.com/redirect/?url=http%3a%2f%2fen.wikipedia.org%2fwiki%2fVisitor_pattern%23Java_example&id=ma-131216214619-60becd27http://pdfcrowd.com/customize/http://pdfcrowd.com/html-to-pdf-api/?ref=pdfhttp://en.wikipedia.org/w/index.php?title=Visitor_pattern&action=edit§ion=15http://en.wikipedia.org/w/index.php?title=Visitor_pattern&action=edit§ion=16http://en.wikipedia.org/wiki/File:Question_book-new.svghttp://en.wikipedia.org/wiki/Wikipedia:Citing_sourceshttp://en.wikipedia.org/wiki/Wikipedia:Verifiabilityhttp://en.wikipedia.org/wiki/Help:Introduction_to_referencing/1http://en.wikipedia.org/wiki/Wikipedia:Verifiability#Burden_of_evidencehttp://en.wikipedia.org/wiki/Separation_of_concernshttp://en.wikipedia.org/wiki/Prettyprintinghttp://en.wikipedia.org/wiki/Programming_languagehttp://en.wikipedia.org/wiki/Compilerhttp://en.wikipedia.org/wiki/Interpreter_(computer_science) -
8/13/2019 En Wikipedia Org Wiki Visitor Pattern Java Example
14/15df di b PRO iAre you a developer? Try out the HTML to PDF API
Wikimedia Commons has mediarelated to Visitor pattern.
The Wikibook Computer ScienceDesign Patternshas a page onthe topic of: Visitorimplementations in various
languages
The Wikibook ComputerScience/Design Patternshas apage on the topic of: Visitorimplementations in various
languages
Related design patterns [edit]
Command pattern: It encapsulates like the visitor pattern one or more functions in an object to present them to a caller.
Unlike the visitor, the command pattern does not enclose a principle to traverse the object structure.
Iterator pattern: This pattern defines a traversal principle like the visitor pattern without making a type differentiation within
the traversed objects.
See also [edit]
Doubleand multiple dispatch
Hierarchical visitor pattern
Function object
Algebraic data type
References [edit]
External links [edit]
The Visitor Family of Design Patterns by Robert C. Martin - a rough chapter
from The Principles, Patterns, and Practices of Agile Software Development,
Robert C. Martin, Prentice Hall
Visitor pattern in UML and in LePUS3 (a Design Description Language)
Article "Componentization: the Visitor Example by Bertrand Meyerand
Karine Arnout, Computer(IEEE), vol. 39, no. 7, July 2006, pages 23-30.
Article A Type-theoretic Reconstruction of the Visitor Pattern
Article "The Essence of the Visitor Pattern " by Jens Palsbergand C. Barry
Jay. 1997 IEEE-CSCOMPSACpaper showing that accept() methods are
unnecessary when reflection is available; introduces term 'Walkabout' for the
technique.
Article "A Time for Reflection " by Bruce Wallace- subtitled "Java 1.2's
reflection capabilities eliminate burdensome accept() methods from your
Visitor pattern"
Visitor Patterns as a universal model of terminating computation.
Visitor Pattern using reflection(java)
http://pdfcrowd.com/http://pdfcrowd.com/redirect/?url=http%3a%2f%2fen.wikipedia.org%2fwiki%2fVisitor_pattern%23Java_example&id=ma-131216214619-60becd27http://pdfcrowd.com/customize/http://pdfcrowd.com/html-to-pdf-api/?ref=pdfhttp://commons.wikimedia.org/wiki/Category:Visitor_patternhttp://en.wikibooks.org/wiki/Computer_Science_Design_Patternshttp://en.wikibooks.org/wiki/Computer_Science_Design_Patterns/Visitorhttp://en.wikibooks.org/wiki/Computer_Science/Design_Patternshttp://en.wikibooks.org/wiki/Computer_Science/Design_Patterns/Visitorhttp://en.wikipedia.org/w/index.php?title=Visitor_pattern&action=edit§ion=17http://en.wikipedia.org/w/index.php?title=Visitor_pattern&action=edit§ion=18http://en.wikipedia.org/w/index.php?title=Visitor_pattern&action=edit§ion=19http://en.wikipedia.org/w/index.php?title=Visitor_pattern&action=edit§ion=20http://en.wikipedia.org/wiki/Command_patternhttp://en.wikipedia.org/wiki/Iterator_patternhttp://en.wikipedia.org/wiki/Double_dispatchhttp://en.wikipedia.org/wiki/Multiple_dispatchhttp://en.wikipedia.org/wiki/Hierarchical_visitor_patternhttp://en.wikipedia.org/wiki/Function_objecthttp://en.wikipedia.org/wiki/Algebraic_data_typehttp://objectmentor.com/resources/articles/visitor.pdfhttp://en.wikipedia.org/w/index.php?title=The_Principles,_Patterns,_and_Practices_of_Agile_Software_Development&action=edit&redlink=1http://en.wikipedia.org/wiki/Robert_C._Martinhttp://www.lepus.org.uk/ref/companion/Visitor.xmlhttp://se.ethz.ch/~meyer/publications/computer/visitor.pdfhttp://en.wikipedia.org/wiki/Bertrand_Meyerhttp://www.cs.bham.ac.uk/~hxt/research/mfps-visitors.pdfhttp://citeseer.ist.psu.edu/palsberg97essence.htmlhttp://en.wikipedia.org/w/index.php?title=Jens_Palsberg&action=edit&redlink=1http://en.wikipedia.org/w/index.php?title=C._Barry_Jay&action=edit&redlink=1http://en.wikipedia.org/wiki/IEEE_Computer_Societyhttp://en.wikipedia.org/wiki/Software_engineeringhttp://www.polyglotinc.com/reflection.htmlhttp://en.wikipedia.org/w/index.php?title=Bruce_Wallace&action=edit&redlink=1http://goblin.colourcountry.net/apt1002/Visitor%20patternshttp://www.oodesign.com/oo_design_patterns/behavioral_patterns/visitor_pattern.html -
8/13/2019 En Wikipedia Org Wiki Visitor Pattern Java Example
15/15
Are you a developer? Try out the HTML to PDF API
Privacy policy About Wikipedia Disclaimers Contact Wikipedia Developers Mobile view
This page w as last modified on 29 November 2013 at 07:19.
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Terms of Useand Privacy Policy.
Wikipedia is a registered trademark of the Wikimedia Foundation, Inc., a non-profit organization.
[hide]V T E
Visitor Pattern using reflection(java).
PerfectJPattern Open Source Project , Provides a context-free and type-safe implementation of the Visitor Pattern in
Java based on Delegates.
Visitor Design Pattern
Article Java Tip 98: Reflect on the Visitor design pattern
Design Patterns
GoF Patterns
Creational Abstract factory Builder Factory method Prototype Singleton
Structural Adapter Bridge Composite Decorator Facade Flyw eight Proxy
BehavioralChain of responsibility Command Interpreter Iterator Mediator Memento Observer State
Strategy Template method Visitor
Concurrency PatternsActive Object Balking Double-checked locking Event-based A synchronous Guarded suspension Join Lock
Monitor Proactor Reactor Read w rite lock Scheduler Thread pool Thread-Specific Storage
Architectural PatternsFront controller Interceptor MVC n-tier Specification Publish-subscribe Naked objects Service Locator
Active record Identity map Data access object Data transfer object
Other Patterns Dependency injection Lazy loading Mock object Null object Object pool Servant Type Tunnel
Books Design Patterns Enterprise Integration Patterns
People Christopher Alexander Erich Gamma Ralph Johnson John Vlissides Grady Booch Kent Beck Ward Cunningham Martin Fowler Robert Martin Jim Coplien Douglas Schmidt Linda Rising
Communities The Hillside Group The Portland Pattern Repository
Categories: Software design patterns
http://pdfcrowd.com/http://pdfcrowd.com/redirect/?url=http%3a%2f%2fen.wikipedia.org%2fwiki%2fVisitor_pattern%23Java_example&id=ma-131216214619-60becd27http://pdfcrowd.com/customize/http://pdfcrowd.com/html-to-pdf-api/?ref=pdfhttp://wikimediafoundation.org/wiki/Privacy_policyhttp://en.wikipedia.org/wiki/Wikipedia:Abouthttp://en.wikipedia.org/wiki/Wikipedia:General_disclaimerhttp://en.wikipedia.org/wiki/Wikipedia:Contact_ushttps://www.mediawiki.org/wiki/Special:MyLanguage/How_to_contributehttp://en.m.wikipedia.org/wiki/Visitor_patternhttp://wikimediafoundation.org/http://www.mediawiki.org/http://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_Licensehttp://wikimediafoundation.org/wiki/Terms_of_Usehttp://wikimediafoundation.org/wiki/Privacy_policyhttp://www.wikimediafoundation.org/http://en.wikipedia.org/wiki/Template:Design_Patterns_patternshttp://en.wikipedia.org/w/index.php?title=Template_talk:Design_Patterns_patterns&action=edit&redlink=1http://en.wikipedia.org/w/index.php?title=Template:Design_Patterns_patterns&action=edithttp://en.wikipedia.org/wiki/Category:Software_design_patternshttp://www.oodesign.com/oo_design_patterns/behavioral_patterns/visitor_pattern.htmlhttp://perfectjpattern.sourceforge.net/dp-visitor.htmlhttp://sourcemaking.com/design_patterns/visitorhttp://www.javaworld.com/javaworld/javatips/jw-javatip98.htmlhttp://en.wikipedia.org/wiki/Software_design_patternshttp://en.wikipedia.org/wiki/Creational_patternhttp://en.wikipedia.org/wiki/Abstract_factory_patternhttp://en.wikipedia.org/wiki/Builder_patternhttp://en.wikipedia.org/wiki/Factory_method_patternhttp://en.wikipedia.org/wiki/Prototype_patternhttp://en.wikipedia.org/wiki/Singleton_patternhttp://en.wikipedia.org/wiki/Structural_patternhttp://en.wikipedia.org/wiki/Adapter_patternhttp://en.wikipedia.org/wiki/Bridge_patternhttp://en.wikipedia.org/wiki/Composite_patternhttp://en.wikipedia.org/wiki/Decorator_patternhttp://en.wikipedia.org/wiki/Facade_patternhttp://en.wikipedia.org/wiki/Flyweight_patternhttp://en.wikipedia.org/wiki/Proxy_patternhttp://en.wikipedia.org/wiki/Behavioral_patternhttp://en.wikipedia.org/wiki/Chain-of-responsibility_patternhttp://en.wikipedia.org/wiki/Command_patternhttp://en.wikipedia.org/wiki/Interpreter_patternhttp://en.wikipedia.org/wiki/Iterator_patternhttp://en.wikipedia.org/wiki/Mediator_patternhttp://en.wikipedia.org/wiki/Memento_patternhttp://en.wikipedia.org/wiki/Observer_patternhttp://en.wikipedia.org/wiki/State_patternhttp://en.wikipedia.org/wiki/Strategy_patternhttp://en.wikipedia.org/wiki/Template_method_patternhttp://en.wikipedia.org/wiki/Concurrency_patternhttp://en.wikipedia.org/wiki/Active_Objecthttp://en.wikipedia.org/wiki/Balking_patternhttp://en.wikipedia.org/wiki/Double-checked_lockinghttp://en.wikipedia.org/wiki/Event-based_Asynchronous_Patternhttp://en.wikipedia.org/wiki/Guarded_suspensionhttp://en.wikipedia.org/wiki/Join-patternhttp://en.wikipedia.org/wiki/Lock_patternhttp://en.wikipedia.org/wiki/Monitor_(synchronization)http://en.wikipedia.org/wiki/Proactor_patternhttp://en.wikipedia.org/wiki/Reactor_patternhttp://en.wikipedia.org/wiki/Read_write_lock_patternhttp://en.wikipedia.org/wiki/Scheduler_patternhttp://en.wikipedia.org/wiki/Thread_poolhttp://en.wikipedia.org/wiki/Thread-Specific_Storagehttp://en.wikipedia.org/wiki/Architectural_patternhttp://en.wikipedia.org/wiki/Front_controllerhttp://en.wikipedia.org/wiki/Interceptor_patternhttp://en.wikipedia.org/wiki/Model_view_controllerhttp://en.wikipedia.org/wiki/Multitier_architecturehttp://en.wikipedia.org/wiki/Specification_patternhttp://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_patternhttp://en.wikipedia.org/wiki/Naked_objectshttp://en.wikipedia.org/wiki/Service_locator_patternhttp://en.wikipedia.org/wiki/Active_recordhttp://en.wikipedia.org/wiki/Identity_maphttp://en.wikipedia.org/wiki/Data_access_objecthttp://en.wikipedia.org/wiki/Data_transfer_objecthttp://en.wikipedia.org/wiki/Dependency_injectionhttp://en.wikipedia.org/wiki/Lazy_loadinghttp://en.wikipedia.org/wiki/Mock_objecthttp://en.wikipedia.org/wiki/Null_object_patternhttp://en.wikipedia.org/wiki/Object_pool_patternhttp://en.wikipedia.org/wiki/Servant_(design_pattern)http://en.wikipedia.org/wiki/Type_Tunnel_patternhttp://en.wikipedia.org/wiki/Design_Patternshttp://en.wikipedia.org/wiki/Enterprise_Integration_Patternshttp://en.wikipedia.org/wiki/Christopher_Alexanderhttp://en.wikipedia.org/wiki/Erich_Gammahttp://en.wikipedia.org/wiki/Ralph_Johnson_(computer_scientist)http://en.wikipedia.org/wiki/John_Vlissideshttp://en.wikipedia.org/wiki/Grady_Boochhttp://en.wikipedia.org/wiki/Kent_Beckhttp://en.wikipedia.org/wiki/Ward_Cunninghamhttp://en.wikipedia.org/wiki/Martin_Fowlerhttp://en.wikipedia.org/wiki/Robert_Cecil_Martinhttp://en.wikipedia.org/wiki/Jim_Coplienhttp://en.wikipedia.org/wiki/Douglas_C._Schmidthttp://en.wikipedia.org/wiki/Linda_Risinghttp://en.wikipedia.org/wiki/The_Hillside_Grouphttp://en.wikipedia.org/wiki/Portland_Pattern_Repositoryhttp://en.wikipedia.org/wiki/Help:Category