When building complex algorithms, it is practical to separate the algorithm from the objects it operates on. The visitor pattern helps achieve such separation. One of the direct effects of using the visitor pattern is the ability to implement multiple distinct operations, without changing the underlying object structure.
The visitor pattern can be described through the series of protocols that each object has to implement:
- Define a Visitable protocol. Elements that can be visited implement this protocol.
- Define a Visitor protocol. Visitor objects implement this protocol, which helps them traverse Visitable objects.
- Extend existing objects to be Visitable.
- Implement one or many Visitor objects and their logic.