I am writing on a GUI program which allows for the visual creation of some configuration file. I have a class hierarchy for the configuration model and I use an object tree of that hierarchy in several different contexts, like for example visual representation of the configuration. I currently use the Visitor pattern to avoid polluting my model classes.
interface IConfigurationElement {
void acceptVisitor(IConfigurationElementVisitor visitor);
}
In an earlier version I used chains of instanceof operators wherever I have a IConfigurationElementVisitor now. Comparing the two solutions I see the following tradeof.
Visitor
- It is easier and safer to add new
IConfigurationElement. Just add a new declaration toIConfigurationElementVisitorand i have compiler errors for all visitor implementations. Withinstanceofyou have to remember where you put it. Basicallyinstanceofviolates the DRY principle as it duplicates logic in several places. - The visitor pattern is more efficient than a chain of
instanceofs
instanceof
- For me, the great advantage of
instanceofcomes with its flexibility. I have more than 5 implementations ofIConfigurationElementbut often need special solutions only for a subset of those.instanceofallows me to handly exactly the special cases special and the rest equal. 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?