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:

    Oh, the holiness of always being the injured party. The historically oppressed can find not only sanctity but safety in the state of victimization. When access to a better life has been denied often enough, and successfully enough, one can use the rejection as an excuse to cease all efforts. After all, one reckons, “they” don’t want me, “they” accept their own mediocrity and refuse my best, “they” don’t deserve me.
    Maya Angelou (b. 1928)

    I thought that a Jewish state would be free of the evils afflicting other societies: theft, murder, prostitution.... But now we have them all. And that’s a thing that cuts to the heart ...
    Golda Meir (1898–1978)

    A multitude of causes unknown to former times are now acting with a combined force to blunt the discriminating powers of the mind, and unfitting it for all voluntary exertion to reduce it to a state of almost savage torpor.
    William Wordsworth (1770–1850)