Design pattern Visitor in a nutshell

Luiz Gustavo De O. Costa
2 min readSep 15, 2019

--

Changes are inevitably (like Thanos quote) and it’s means more code, deploy etc, in a short is more money to spend to maintain your system up and running. In this article I’ll present a design pattern to help you when a change arrives, the Visitor pattern.

Camp Nou stadium — FCB

1. What this pattern is?

Define a new operation without changing the classes of the elements on which it operates[1].

By Ian Darwin[4] the definition is Perform one or more operations on a collection of different data types without disrupting existing code.

[5]The visitor pattern is useful when you want to process a data structure containing different kinds of objects, and you want to perform a specific operation on each of them, depending on its type.

2. When use it?

As the section above says, when you had to add new operations without changing the classes of the elements.

To example purpose, let’s use this example to start a professional soccer match with referee match check:

  • Some player data
  • Match time and date
  • Team uniform color

After all is possible add new operations into concrete visitor and nothing will be break on element (node) side whereas the visitor and element are decoupled.

3. Class diagram

3.1. GOF

The code for this class diagram is here.

GOF diagram + params

3.2. Example

The code for this example is here.

4. Code

NodeMatch aka Element
ConcreteElement
Visitor interface
ConcreteVisitor

5.Code

The complete code is available on github.

6.Enviroment

  • openJDK 11,
  • Lombok,
  • IntelliJ

If you like it, give your applause and share it.

7. References

[1]John Vlissides, Ralph Johnson, Richard Helm, Erich Gamma, 1994. Design Patterns: Elements of Reusable Object-Oriented Software

[2]Kathy Sierra, Bert Bates, Elisabeth Robson, Eric Freeman, 2004. Head First Design Patterns

[3]Szczukocki, Denis. Visitor Design Pattern in Java.https://www.baeldung.com/java-visitor-pattern. Accessed June 13, 2019.

[4] Darwin, Ian. The Visitor Design Pattern in Depth. https://blogs.oracle.com/javamagazine/the-visitor-design-pattern-in-depth. Accessed September 11, 2019.

[5]https://softwareengineering.stackexchange.com/questions/333692/understanding-the-need-of-visitor-pattern. Accessed July 10, 2021.

[6] Cover image, https://unsplash.com/photos/C-TNT-R0cho.

--

--

Luiz Gustavo De O. Costa
Luiz Gustavo De O. Costa

Written by Luiz Gustavo De O. Costa

Hey friend!! I’m Luiz Gustavo, a Java developer and I’m here to learn and write about Java, tests and good practices

No responses yet