Suppose you have an abstract BaseClass
and some derived classes and that you need to visit a List<BaseClass>
with a Visitor
. The code would be:
class Visitor
{
public void Visit(Derived1 visitable) { /*do something*/ }
public void Visit(Derived2 visitable) { /*do something*/ }
public void Visit(Base visitable) { thrown new InvalidOperationException(); }
//other derivatives
}
class Base
{
public virtual void Accept(Visitor visitor) { visitor.Visit(this); }
}
class Derived1 : Base
{
//override is mandatory to have Visit(Derived1 visitable) called
public override void Accept(Visitor visitor) { visitor.Visit(this); }
}
class Derived2 : Base
{
//override is mandatory to have Visit(Derived2 visitable) called
public override void Accept(Visitor visitor) { visitor.Visit(this); }
}
Then you can use all this stuff in a method like:
var baseClassList = new List<BaseClass>();
//fill baseClassList somehow
var visitor = new Visitor();
foreach(var visitable in baseClassList)
visitable.Accept(visitor);
I think this is a bit too much for a simple dispatching of some operations on different derived classes.
Also, it is counter-intuitive that the chain starts from calling Accept
and not Visit
.
Also, if you add a new Derived3
class, you always have to do 2 things: a new overload in the Visitor
AND the override of the Accept
method in the new derived class. Often you forget the second point, getting a runtime error, and other annoying things.
I'm looking for some simpler and less verbose and more secure implementation of a Visitor
pattern in C#. Is it possible?