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:
“A state of war or anarchy, in which law has little force, is so far valuable, that it puts every man on trial. The man of principle is known as such, and even in the fury of faction is respected.”
—Ralph Waldo Emerson (18031882)
“It should be noted that when he seizes a state the new ruler ought to determine all the injuries that he will need to inflict. He should inflict them once and for all, and not have to renew them every day.”
—Niccolò Machiavelli (14691527)
“My generation, dear Ron, swore on the Altar of God that whoever proclaims the intent of destroying the Jewish state or the Jewish people, or both, seals his fate.”
—Menachem Begin (19131992)