Easy patterns: Visitor

Ruslan Malogulko
ITNEXT
Published in
2 min readJul 16, 2018

--

This article is created in continuation to series of easy patterns description and describes behavioral pattern for separation between classes and operations they perform.

Currently you can find articles for such patterns:

Creational patterns:

Simple Factory

Factory method

Builder

Singleton

Abstract factory

Prototype

Structural patterns:

Adapter

Decorator

Bridge

Composite

Facade

Flyweight

Proxy

Behavioral patterns:

Visitor (this article)

Mediator

Observer

Memento

Iterator

Chain Of Responsibility

Strategy

State

The main essence

The main idea of Visitor pattern is to separate classes from logic they are performing. This helps in adding new logic without changing class itself (Open/closed principle of SOLID).

To implement this pattern you need two types of participants:

  • visitor — declares operations for concrete classes. Name of each operation should contain signature of specific class that would send visit request to the visitor.
  • element — defines an Accept operation that takes visitor as argument.

Example of use

In this example we implemented base visitor and element classes. After we implemented concrete elements for working with console.log, alert and notification system and concrete visitor which able to do all work related to notification through such channels to us. Right after we instantiated elements and visitor and called on each visitor accept method passing visitor instance as an argument, we can see output in console, in alert modal and through notification api.

So, you can see, passing another visitor instance to accept method brings some another functionality to each element class (which stays untouched because all logic is delegated to specific visitor).

Profit

  1. Visitor makes adding new operations easier. You can define a new operation over the object structure just by adding new visitor. Without this pattern if you spread logic between many classes and decided to add new operation, you should do that for each class.
  2. Visitor pattern helps to gather related operations and separate unrelated ones. Unrelated operations should be set in separate visitor subclasses.
  3. Accumulating Element state. As far as visitor visits each element in object structure, it’s super easy to accumulate state based on called operations.

Weak places

  1. However adding new Element classes is harder than usual. Each new element motivates you to add new operation to visitor as well.
  2. Visitor pattern often breaks encapsulation. It assumes that elements let visitor do its job by providing public operations for accessing an element’s internal state. This potentially can compromise its encapsulation.

Conclusion

If you found this article helpful, please hit the 👏 button and feel free to comment below!

--

--