Card 09/ 09
Recap: Visitor Pattern
Operations become classes, double dispatch picks the method, and new element types cost the most.
Visitor puts each operation over a set of classes into a class of its own.
- Intent. Add operations over element classes without changing those classes.
- Participants. A visitor interface with one method per element class, concrete visitors with one operation each, and elements whose
acceptcalls the method for their own class. - Double dispatch.
acceptchooses by the element's class; the visit call inside it chooses by the visitor's class. - In Python.
ast.NodeVisitorfinds the method by name,visit_plus the class name;singledispatchandmatchneed noacceptat all. - The trade-off. A new operation is one class; a new element class edits every visitor.
- When not. Element classes that change often, or only one or two operations.
← → move through sections and cards