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:

    The State must follow, and not lead, the character and progress of the citizen.
    Ralph Waldo Emerson (1803–1882)

    Being the dependents of the general government, and looking to its treasury as the source of all their emoluments, the state officers, under whatever names they might pass and by whatever forms their duties might be prescribed, would in effect be the mere stipendiaries and instruments of the central power.
    Andrew Jackson (1767–1845)

    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 (1820–1895)