7.2 VISITOR PATTERN
The visitor pattern is popular in financial software designs for two of its features:
- It allows us to extend the functionality of classes without modifying their structure or interface.
- It provides a viable solution to the lack of double dispatch in common object-oriented languages like Java and C++, which provide only single dispatch through virtual functions. In single dispatch, the compiler chooses the right function at run-time using the dynamic type of calling object.
In order to give us the flexibility of adding new operations to classes, the visitor pattern lets us separate their structure from their algorithms. We then list the operations (algorithms) in an aggregate visitor class, declaring them as all pure virtual, so that we need to implement them in the classes we derive from it. For customized operations, we derive a concrete visitor from the abstract visitor class, which has a call accept() that takes the object this as its argument. Knowing the type of the caller (through the this argument) and the function (through the virtual function resolution), the accept() call simulates double dispatch. Moreover, the derived visitor class is under our control, giving us the freedom to add functionality as we see fit.

Figure 7.3 Visitor pattern as it applies to a trading platform. The UML diagram corresponds to the code listing below
As an example, we show ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access