Member-only story

Design Patterns in Go: Visitor

ZhangJie (Kn)
3 min readNov 16, 2024

--

Visitor Pattern

Behavioral Patterns target issues related to communication and interaction between objects. They focus on defining protocols for collaboration among objects that are often too complex to design statically, enabling dynamic delegation of responsibilities at runtime.

OK, Let’s go through the description of the 10th behavioral pattern — Observer Pattern.

Context:

The Visitor pattern is useful when you need to define new operations on an object structure composed of classes that are difficult to modify, like third party classes or legacy code.

By encapsulating the new behavior in a Visitor, you can add new operations without changing the existing element classes.

Solution:

  • Define a Visitor interface declaring visit methods for each Element type
  • Each ConcreteVisitor implements the visit methods to perform specific operations
  • The Element interface declares an accept(Visitor) method to direct a visitor to itself
  • Each ConcreteElement implements accept() by calling the visitor’s visit method
  • Client creates ConcreteVisitor and passes it to object structure root which propagates it to all child elements

--

--

ZhangJie (Kn)
ZhangJie (Kn)

No responses yet