7.2 VISITOR PATTERN

The visitor pattern is popular in financial software designs for two of its features:

  1. It allows us to extend the functionality of classes without modifying their structure or interface.
  2. 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.

image

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 ...

Get Principles of Quantitative Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.