I am working on a GUI application which generates a configuration file. I have a class hierarchy for the configuration model and I use an object tree of that hierarchy in several different contexts. Currently, I use the Visitor pattern to avoid polluting my model classes with context specific code.
interface IConfigurationElement {
void acceptVisitor(IConfigurationElementVisitor visitor);
}
In an earlier version I used chains of instanceof
conditions instead of the Visitor. Comparing the two approaches I see the following tradeofs.
Visitor
- It is easier and safer to add new
IConfigurationElement
. Just add a new declaration toIConfigurationElementVisitor
and the compiler generates errors for all visitor implementations. Withinstanceof
chains you have to remember all the places you have to extend with the new configuration element. Basicallyinstanceof
violates the DRY principle as it duplicates logic in several places. - The visitor pattern is more efficient than a chain of
instanceof
conditions
instanceof
- The great advantage of
instanceof
is its flexibility. For exampleinstanceof
allows me to define special solutions for different subsets ofIConfigurationElement
implementations which need to be handled similarilly in some cases. In contrast, Visitor forces me to implement a method for each implementation class every time.
Is there a common solution for this kind of problem? Can I adapt the Visitor somehow, so I can provide a common solution for some cases?