Design Patterns – Expandable Alternative to Visitor Pattern for Tree Traversal

cc++11design-patternstrees

I have a tree containing various subtypes of the my base node class. I now want to traverse this tree and do something with the nodes depending on their type.

The most straightforward idea is to just define a method doSomething in my base node class, but this means that to add functionality I have to add a method to all existing node subtypes.

The first thing that comes to mind to solve this is the Visitor pattern. However, I want to be able to create new subtypes without having to change all existing visitors – I want the new subtypes to inherit the way they are handled from their base type.

I think using dynamic_cast should do the trick, but I understood that it is a costly operation, and it will be called a lot, so that is not a good solution. And many people say it is a sign of bad design, although I do not see the problem in this case.

At this moment I am using the first solution as I see foresee much more added types than functionality, but is there a better way to do this?

Best Answer

I want the new subtypes to inherit the way they are handled from their base type

The classic GOF visitor pattern behaves exactly like that. For example, look the Wikipedia CarElement example (it is a Java example, but the important part is similar in C++). Lets assume you add new Wheel types like SquareWheel, RoundWheel by inheriting them from Wheel. Then, visit(Wheel &wheel) will process SquareWheel as well as RoundWheel, as long as you do not define any methods visit(SquareWheel &wheel) or visit(RoundWheel &wheel).