Unformatted text preview: on a Composite structure Again problem with external iterators, because traversal algorithm may be nontrivial Solution: Use internal iteration (let aggregate handle iteration in one shot) or cursor-type iterators (let aggregate deGine the next object to be processed; store only iteration status in iterator) In the second case, the composite must provide a fairly rich tree-based protocol (e.g., Gind father, children, siblings of a node, etc.) 89 Group of related objects must support many kinds of operations Examples: Lexi glyphs must support formatting, spell-checking, hyphenation, etc. All numeric classes in a programming language must support addition, subtraction, multiplication, etc. All syntax objects in a syntax tree must support code generation, metrics computation, data Glow analysis, etc. 90 Visitor pattern: The nave solution An example: Visiting an abstract syntax tree Node TypeCheck() GenerateCode() PrettyPrint() Pattern Visitor pattern Problems of the nave solution: Pattern -- Information about various functions is distributed across many (element) classes -- Hefty element classes (each getting a new protocol for each function) -- Hard to understand and maintain code ...
AssignmentNode TypeCheck() GenerateCode() PrettyPrint() AssignmentNode TypeCheck() GenerateCode() PrettyPrint()
91 -- Hard to add new functions Better solution: -- Encapsulate each function in a class (called a visitor) -- Create abstract superclass for all visitor classes 92 Visitor pattern (cont
Applicability d) Pattern Pattern Visitor pattern Applicability (cont d) An additional example of applicability (compiler) Actions to type-check program to be compiled depend on each construct. The same is true when generating object code, computing metrics, etc. A group of related objects must each support different kinds of operations Caveat: The actual method executed depends both on the class of the receiving object and the operation being performed Example: (numeric classes) Actual code executed depends both on the class of receiver and argument 3 + 5 does integer addition 3 + 5.5 Gloating point addition 93 94 Visitor p...
View Full Document
This note was uploaded on 02/23/2012 for the course COMP 553 taught by Professor Ajay during the Spring '12 term at Ill. Chicago.
- Spring '12