This article is one part of a series about the Visitor pattern. Please read the previous articles to get an overview about the pattern and to get the needed basics to understand this article.

The example implementation of this article is focused on the Visitor pattern. To keep the example as short as possible I intentional ignored some mandatory programming guidelines. Therefore, please keep in mind that the implementation should show the idea of the Visitor pattern but it ignores things like const correctness, private members or RAII (resource acquisition is initialization).

Complete visitor

Within the previous articles we have seen two use cases for the Visitor pattern: enumeration and dispatching. For each use case, we have implemented an according Visitor. In the context of these implementations we have seen that the Visitor pattern is over-engineering for the single use cases. There exist lightweight patterns exactly matching such single tasks. But if the two uses cases come together, the Visitor pattern may be appropriate. Therefore, only in this case we have a “complete” Visitor which unites enumeration and dispatching features.

For the enumeration feature, we will use two generic enumerator Visitors. One will enumerate all elements and the other one will additionally filter distinct elements and therefore enumerate each object instance only once.

Bases on the generic enumeration Visitors we can implement the query functions as dispatching Visitors. Here we have two queries. One will list the complete order history and the other one an overview with the ordered elements.

The implemented Visitor contains enumeration and dispatching of the elements. The implementation has the same complexity as the ones seen in the previous examples which solved one use case only. But this time the disadvantage of the complex pattern is exceeded by the advantage that we can solve both use cases at once. The Visitor pattern will match perfectly with this kind of implementation task and therefore it can show its strength.

But of course, there are still some open questions. For example: Will it be easy to add new elements? How can we write queries which have to access some other properties of the data container, like the count of ordered elements? Can we reuse enumerator Visitors?

We will look at these questions soon and see whether the Visitor pattern is suitable to solve these use cases or whether we reach the borders of the pattern.

Outlook

Within the next articles we want to analyze some advanced topics, like reusable enumerator Visitors or Visitors which can access not visitable elements of the data container.