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:
“The classicist, and the naturalist who has much in common with him, refuse to see in the highest works of art anything but the exercise of judgement, sensibility, and skill. The romanticist cannot be satisfied with such a normal standard; for him art is essentially irrationalan experience beyond normality, sometimes destructive of normality, and at the very least evocative of that state of wonder which is the state of mind induced by the immediately inexplicable.”
—Sir Herbert Read (18931968)
“Wherever the State touches the personal life of the infant, the child, the youth, or the aged, helpless, defective in mind, body or moral nature, there the State enters womans peculiar sphere, her sphere of motherly succor and training, her sphere of sympathetic and self-sacrificing ministration to individual lives.”
—Anna Garlin Spencer (18511931)
“The stars which shone over Babylon and the stable in Bethlehem still shine as brightly over the Empire State Building and your front yard today. They perform their cycles with the same mathematical precision, and they will continue to affect each thing on earth, including man, as long as the earth exists.”
—Linda Goodman (b. 1929)