Unformatted text preview: attern (cont
Applicability d) Pattern Visitor VisitElementA() VisitElementB() Pattern Many distinct categories of operations must be supported by an object structure, but we wish to keep interfaces small (Important) Object structure does not change often, but operations are added or changed frequently Structure Two class hierarchies, one for object structure, one for operation family Numeric class example: Object class would have subclasses Integer, Float, Rational, etc. Operation classes would have Multiplication, Addition, etc. 95 ...
ConcreteVisitor1 VisitElementA(ElementA) VisitElementB(ElementB) ConcreteVisitor2 VisitElementA(ElementA) VisitElementB(ElementB) Element
ObjectStructure Accept(Visitor) Structure of Visitor pattern ConcreteElementA Accept(Visitor v) OperationA() ConcreteElementB Accept(Visitor v) OperationB() v->VisitElementA(this) v->VisitElementB(this) 96 Interaction diagram of Visitor aStructure! aElementA! aElementB!
VisitElementA(aElementA) Pattern Pattern Visitor pattern (cont
aVisitor! d) Consequences 1. Adding new operations is easy (kind of) Must add a new operation subclass with a method for each concrete element class... Yet, that s easier than having to modify every element class (which happens when visitor hierarchy is not deGined) 2. Visitor coagulates different ways of performing a given operation, depending on the object receiving the operation Methods for each operation are in the same concrete visitor subclass Accept(aVisitor) OperationA() Accept(aVisitor) VisitElementB(aElementB) OperationB() 97 98 Pattern Visitor pattern Consequences (cont d) 3. Adding new concrete elements is difGicult Must add a new method to each concrete visitor subclass Recompile each class 4. Visitors can accumulate state and visit elements without a common ancestor (which matters in statically-typed languages like C++) Iterator would not work unless identiGier of common superclass can be used (e.g., because an iterator must invoke protocol of object receiving an operation explicitly) 99 Visitor pattern (cont
View Full Document
- Spring '12
- Object-Oriented Programming, Design pattern, Subroutine