The Visitor Pattern – Part 4

The interface approach introduced in Part 2 of this series and extended in Part 3 did cover most of our needs. But there is nothing that can’t be done better with the right tools.

I’ve been using this approach for a couple of years and it made my life a lot easier. You need an export as DXF? No problem! Displaying in OpenGL? I’ll write a new visitor!

Writing the additional interfaces was easy done with the help of a customized code template, so that has never been a pain. The only thing that bothered me over time was that I could only apply the Visitor Pattern to classes I have control of. I just wasn’t able to visit, say, all the components of a TForm in a descent fashion (i.e. not queueing if component is something then <typecast>).

While digging through the new features of Delphi 2010 I discovered a solution which is as clean, lean, flexible and elegant as it could be. A little RTTI and some decent naming convention did the trick. Here is the code:

And here is a visitor capable of handling some VCL controls on a form together with an example of its usage:

If you need to visit some class, just introduce a new method with a suitable name and signature and you are done. No new interfaces, no fiddling around with classes. It just works right out of the box.

I’m still visualizing some possible scenarios where this approach can be useful, too. Stay tuned.

Author: Uwe Raabe

Addicted to Pascal/Delphi since the late 70's