* Made minor changes in some patterns such as removed throws clause where not needed, changed incorrect order of arguments in assertEquals * Minor refactorings and code style changes. 1) Removed several use of raw types 2) Removed unnecessary throws clauses 3) Used lambda expressions wherever applicable 4) Used apt assertion methods for readability 5) Use of try with resources wherever applicable 6) Corrected incorrect order of assertXXX arguments * Removed unused import from Promise * Addressed review comments * Addressed checkstyle issue
layout, title, folder, permalink, categories, tags
layout | title | folder | permalink | categories | tags | |||
---|---|---|---|---|---|---|---|---|
pattern | Visitor | visitor | /patterns/visitor/ | Behavioral |
|
Intent
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.
Applicability
Use the Visitor pattern when
- an object structure contains many classes of objects with differing interfaces, and you want to perform operations on these objects that depend on their concrete classes
- many distinct and unrelated operations need to be performed on objects in an object structure, and you want to avoid "polluting" their classes with these operations. Visitor lets you keep related operations together by defining them in one class. When the object structure is shared by many applications, use Visitor to put operations in just those applications that need them
- the classes defining the object structure rarely change, but you often want to define new operations over the structure. Changing the object structure classes requires redefining the interface to all visitors, which is potentially costly. If the object structure classes change often, then it's probably better to define the operations in those classes
Real world examples
- Apache Wicket component tree, see MarkupContainer
- javax.lang.model.element.AnnotationValue and AnnotationValueVisitor
- javax.lang.model.element.Element and Element Visitor
- java.nio.file.FileVisitor