State
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 action performed on the object depends on previous such actions.
An example of this is a pretty-printer in a programming language implementation (such as a compiler or 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 level can 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.
Read more about this topic: Visitor Pattern
Famous quotes containing the word state:
“If a hermit lives in a state of ecstasy, his lack of comfort becomes the height of comfort. He must relinquish it.”
—Jean Cocteau (18891963)
“We hear the Secretary of State boasting of his brinkmanshipthe art of bringing us to the edge of the abyss.”
—Adlai Stevenson (19001965)
“No healthy man, in his secret heart, is content with his destiny. He is tortured by dreams and images as a child is tortured by the thought of a state of existence in which it would live in a candy store and have two stomachs.”
—H.L. (Henry Lewis)