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:

    Irish? In truth I would not want to be anything else. It is a state of mind as well as an actual country. It is being at odds with other nationalities, having quite different philosophy about pleasure, about punishment, about life, and about death. At least it does not leave one pusillanimous.
    Edna O’Brien (b. c. 1932)

    I am willing to pledge myself that if the time should ever come that the voluntary agencies of the country together with the local and state governments are unable to find resources with which to prevent hunger and suffering ... I will ask the aid of every resource of the Federal Government.... I have the faith in the American people that such a day will not come.
    Herbert Hoover (1874–1964)

    Beluthahatchee is a country where all unpleasant doings and sayings are forgotten, a land of forgiveness and forgetfulness. When a woman accusingly reminds her man of something in the past, he replies, ‘I thought that was in Beluthahatchee.’ Or a person may say to another, to dismiss some matter, “Oh, that’s in Beluthahatchee.’
    —For the State of Florida, U.S. public relief program (1935-1943)