Let’s say we have a classical polymorphic architecture :
class Animal
{
virtual void eat() = 0;
};
class Frog : public Animal
{
virtual void eat() { ... }
};
class Chipmunk : public Animal
{
virtual void eat() { ... }
};
This is fine. But when it comes to rendering, I could add a virtual render method to the Animal base class just like the eat method.
But then animals source files have dependencies to the particular library that is being used. This doesn’t make things modulable and maintainable. Plus, their rendering code basically doesn’t concern them.
What is a nice way of putting the render specific code out of the derived classes ?
When I say nice, I mean without using something like an overloaded method that returns a different number for each derived class so I can do a big if…else if ….
Have a look at the Visitor Pattern – The virtual
render()function is passed an instance of aVisitor, and then callsVisitor.renderMe(this). Visitor then overloadsrenderMeas needed and contains the rendering specific code.