ArticleslgStudy

computer science

Visitor pattern

Visitor pattern is a computer science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Visitor pattern rather than just read about it. In short: A visitor pattern is a software design pattern that separates the algorithm from the object structure. Because of this separation, new operations can be added to existing object structures without modifying the structures.

Visitor pattern — main illustration
Visitor pattern — illustration

Key takeaways

  • Visitor pattern belongs to computer science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Visitor pattern to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Visitor pattern from memory before moving on to harder problems.

Reference excerpt

A visitor pattern is a software design pattern that separates the algorithm from the object structure. Because of this separation, new operations can be added to existing object structures without modifying the structures. It is one way to follow the open/closed principle in object-oriented programming and software engineering. In essence, the visitor allows adding new virtual functions to a family of classes, without modifying the classes. Instead, a visitor class is created that implements all of the appropriate specializations of the virtual function. The visitor takes the instance reference as input, and implements the goal through double dispatch. Programming languages with sum types and pattern matching obviate many of the benefits of the visitor pattern, as the visitor class is able to both easily branch on the type of the object and generate a compiler error if a new object type is defined which the visitor does not yet handle.

Overview The Visitor design pattern is one of the twenty-three Gang of Four design patterns.

Problems the pattern can solve It should be possible to define a new operation for (some) classes of an object structure without changing the classes. When new operations are needed frequently and the object structure consists of many unrelated classes, it's inflexible to add new subclasses each time a new operation is required because "distributing all these operations across the various node classes leads to a system that's hard to understand, maintain, and change."

Solution described by the pattern Define a separate (visitor) object that implements an operation to be performed on elements of an object structure. Clients traverse the object structure and call a dispatching operation accept (visitor) on an element — that "dispatches" (delegates) the request to the "accepted visitor object". The visitor object then performs the operation on the element ("visits the element"). This makes it possible to create new operations independently from the classes of an object structure by adding new visitor objects. See also the UML class and sequence diagram below.

Definition The Gang of Four defines the Visitor as:

Represent[ing] an operation to be performed on elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates. The nature of the Visitor makes it an ideal pattern to plug into public APIs, thus allowing its clients to perform operations on a class using a "visiting" class without having to modify the source.

Advantages Moving operations into visitor classes is beneficial when

many unrelated operations on an object structure are required, the classes that make up the object structure are known and not expected to change, new operations need to be added frequently, an algorithm involves several classes of the object structure, but it is desired to manage it in one single location, an algorithm needs to work across several independent class hierarchies. A drawback to this pattern, however, is that it makes extensions to the class hierarchy more difficult, as new classes typically require a new visit method to be added to each visitor.

Application Consider the design of a 2D computer-aided design (CAD) system. At its core, there are several types to represent basic geometric shapes like circles, lines, and arcs. The entities are ordered into layers, and at the top of the type hierarchy is the drawing, which is simply a list of layers, plus some added properties. A fundamental operation on this type hierarchy is saving a drawing to the system's native file format. At first glance, it may seem desirable to add local save methods to all types in the hierarchy. But it can also be useful to save drawings to other file formats. Adding ever more methods for saving into many different file formats can complicate the original geometric data structure. A naive way to solve this would be to maintain separate functions for each file format. Such a save function would take a drawing as input, traverse it, and encode into that specific file format. As this is done for each added different format, duplication between the functions accumulates. For example, saving a circle shape in a raster format requires very similar code no matter what specific raster form is used, and is different from other primitive shapes. The case for other primitive shapes like lines and polygons is similar. Thus, the code becomes a large outer loop traversing through the objects, with a large decision tree inside the loop querying the type of the object. Another problem with this approach is that it is very easy to miss a shape in one or more savers, or a new primitive shape is introduced, but the save routine is implemented only for one file type and not others, leading to code extension and maintenance problems. As the versions of the same file grows it becomes more complicated to maintain it. Instead, the visitor pattern can be applied. It encodes the logical operation (i.e. save(image_tree)) on the whole hierarchy into one class (i.e. Saver) that implements the common methods for traversing the tree and describes virtual helper methods (i.e. save_circle, save_square, etc.) to be implemented for format specific behaviors. In the case of the CAD example, such format specific behaviors would be implemented by a subclass of Visitor (i.e. SaverPNG). As such, all duplication of type checks and traversal steps is removed. Additionally, the compiler now complains if a shape is omitted since it is now expected by the common base traversal/save function.

Iteration loops

The visitor pattern may be used for iteration over container-like data structures just like Iterator pattern but with limited functionality. For example, iteration over a directory structure could be implemented by a function class instead of more conventional loop pattern. This would allow deriving various useful information from directories content by implementing a visitor functionality for every item while reusing the iteration code. It's widely employed in Smalltalk systems and can be found in C++ as well. A drawback of this approach, however, is that you can't break out of the loop easily or iterate concurrently (in parallel i.e. traversing two containers at the same time by a single i variable). The latter would require writing additional functionality for a visitor to support these features.

Structure

UML class and sequence diagram

… excerpt ends here. Continue reading the full article.

Illustrations

Visitor pattern: Visitor in Unified Modeling Language (UML).[5]: 381
Visitor in Unified Modeling Language (UML).[5]: 381
Visitor pattern: Visitor in LePUS3 (legend)
Visitor in LePUS3 (legend)
Visitor pattern illustration

Worked examples

Example 1 — a first encounter with Visitor pattern

Start with the simplest possible case. Write down what Visitor pattern claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In computer science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Visitor pattern before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Visitor pattern ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Visitor pattern

In research
Visitor pattern appears in computer science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Visitor pattern in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Visitor pattern is common in secondary-school and first-year university syllabi. It links to neighbouring topics Programming language comparisons, Software design patterns, so understanding it makes those chapters shorter.
In everyday life
Look for Visitor pattern outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.
Ask Teacher Smith questions about this articleOpens your AI tutor with a question about “Visitor pattern” →

How to study Visitor pattern in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Visitor pattern means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Visitor pattern out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Visitor pattern in simple terms?

A visitor pattern is a software design pattern that separates the algorithm from the object structure. Because of this separation, new operations can be added to existing object structures without modifying the structures.

Why does Visitor pattern matter?

Because it connects several computer science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Visitor pattern?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Visitor pattern.

Tags

  • Programming language comparisons
  • Software design patterns

Keep exploring