Visitor Pattern - State

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:

    Every country has its own constitution; ours is absolutism moderated by assassination.
    —Anonymous Russian. Quoted in Count Münster, Political Sketches of the State of Europe 1814-1867 (1868)

    It is said that a carpenter building a summer hotel here ... declared that one very clear day he picked out a ship coming into Portland Harbor and could distinctly see that its cargo was West Indian rum. A county historian avers that it was probably an optical delusion, the result of looking so often through a glass in common use in those days.
    —For the State of New Hampshire, U.S. public relief program (1935-1943)

    The Indian attitude toward the land was expressed by a Crow named Curly: “The soil you see is not ordinary soil—it is the dust of the blood, the flesh, and the bones of our ancestors. You will have to dig down to find Nature’s earth, for the upper portion is Crow, my blood and my dead. I do not want to give it up.”
    —For the State of Montana, U.S. public relief program. Montana: A State Guide Book (The WPA Guide to Montana)