I know what Visitor Pattern is and how to use it; this question is not a duplicate of this one.
I've got a library where I put most of the reusable code I write, and which I link to most of my projects.
Often I need to add features to some classes, but without adding these new features to the library. Let me use a real example:
In this lib I've got a class Shape
, inherited by CircleShape
, PolygonShape
and CompositeShape
.
I'm now developing a graphical application where I need to render these Shape
, but don't want to put a virtual function render
in the core Shape
class, since some of my projects which use Shape
don't do any rendering, and other graphical projects could use different rendering engines (I'm using Qt for this project, but for a game I'd use OpenGL, thus the render
function will need different implementations).
The most famous way to do this is using Visitor Pattern, of course, but this pops a few doubts into my mind:
Any class of any library could need to be extended as my Shape
does. Most of the public libraries (about all of them) don't provide any support for Visitor Pattern; why? why should I?
Visitor Pattern is a way to simulate Double Dispatching in C++. It's not native in C++, and requires to be explicitly implemented, making the class interface more complex: I don't think the applyVisitor
function should be at the same level of my class' functions, I see this like breaking abstraction.
Explicitly up-casting Shape
with dynamic_cast
is more expensive, but to me it looks like a cleaner solution.
So, what should I do? Implementing Double Dispatching in all my library classes? What if the library providing Shape
wasn't mine, but some GPL library found on the internet?