1.10 The Visitor Pattern
Keywords: current

Next: 1.10.1 Interpreting Arithmetic Expressions Up: 1. From C++ to Previous: 1.9.4 Name and Method

#
1.10 The Visitor Pattern

The composite and interpreter patterns enforce an elegant discipline for writing object-oriented functional programs. But this elegance comes at a price: every time we need to define a new operation we must modify every class in the composite class hierarchy to add a new method. As a result, program modification involving new methods is painful. Moreover, we cannot use these patterns to define new operations if we do not control the source code for the composite class. Without access to the source code, the only way we can define new methods is to write them in procedural style as static methods in another class, losing all the benefits of object-oriented organization.

In this section, we introduce a design pattern, called the visitor pattern, that completely and elegantly solves the problem of adding new operations to composite class hierarchies without modifying the text of either the composite class or its variants.

Before delving into the technical definition of the visitor pattern, we present a motivating example: an interpreter for arithmetic expressions.

Subsections

- 1.10.1 Interpreting Arithmetic Expressions
- 1.10.2 Openness in Data Design
- 1.10.3 Polymorphic Visitors
- 1.10.4 Polymorphic Visitors with Arguments

Next: 1.10.1 Interpreting Arithmetic Expressions Up: 1. From C++ to Previous: 1.9.4 Name and Method