1

I have a large collection of different objects that extend the same base class A. To apply different algorithms to the collection, I created an IVisitor interface that has an Accept method for each child of A.

Some of the visitors that implement IVisitor actually use all children of A but many of them don't, so I end up having visitors with a bunch of empty (noop) methods that I would like to avoid. Moreover, everytime I add a new child class of A I need to add a new Accept method to IVisitor and all the classes implement it, which is a common problem of the visitor pattern.

I've tried to implement the Selective Visitor pattern but I don't like to cast objects around as in my case it could be a problem.

I've also evaluated this question but its answers are not really target the problem. I would like to use an interface instead of an abstract class, because in my case multiple inheritance is not allowed.

Is there a way to avoid this kind of hassle and get a cleaner code?

EDIT: Here you find an example on Draw.io

SeeEn
  • 41
  • 5

1 Answers1

2

You can define a new pattern ;) for your case: "Selective Generic Visitor". You can have only one Visit method in your IVisit interface that accepts a generic parameter with constraint inherited from BaseClass.

interface IVisitor<T> where T:BaseClass
{
    void Visit(T element);
}

Then Concrete visitors can specify the generic parameter and implement the Visit method. If you can take advantage an IoC container such as Autofac, It serves you as a factory for generic types and easily you can get the proper Visitor instance by requesting IVisitor and pass it to Accept method calls.

Polymorphic
  • 420
  • 3
  • 14