You are here

The Visitor Pattern

26 July, 2019 - 09:51
Available under Creative Commons-ShareAlike 4.0 International License. Download for free at

The visitor pattern is a pattern for communication and collaboration between two union patterns: a "host" union and a "visitor" union. An abstract visitor is usually defined as an interface in Java. It has a separate method for each of the concrete variant of the host union. The abstract host has a method (called the "hook") to "accept" a visitor and leaves it up to each of its concrete variants to call the appropriate visitor method. This "decoupling" of the host's structural behaviors from the extrinsic algorithms on the host permits the addition of infinitely many external algorithms without changing any of the host union code. This extensibility only works if the taxonomy of the host union is stable and does not change. If we have to modify the host union, then we will have to modify ALL visitors as well!

Figure 3.3 The visitor pattern

All the "state-less" visitors, that is visitors that contain no non-static fields should be single¬tons. Visitors that contain non-static fields should not be singletons.