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:
“People think they have taken quite an extraordinarily bold step forward when they have rid themselves of belief in hereditary monarchy and swear by the democratic republic. In reality, however, the state is nothing but a machine for the oppression of one class by another, and indeed in the democratic republic no less than in the monarchy.”
—Friedrich Engels (18201895)
“While you are nurturing your newborn, you need someone to nurture you, whether it is with healthful drinks while youre nursing, or with words of recognition and encouragement as you talk about your feelings. In this state of continual giving to your infantwhether it is nourishment or care or loveyou are easily drained, and you need to be replenished from sources outside yourself so that you will have reserves to draw from.”
—Sally Placksin (20th century)
“Thou knowest in the state of innocency Adam fell, and what
should poor Jack Falstaff do in the days in villainy?”
—William Shakespeare (15641616)