Every example of the visitor pattern that I see uses abstract classes. One of the major drawbacks of the visitor pattern is the fact that each visitor must implement a .visit method for every acceptor it wants to visit. Another drawback is now every acceptor must implement .accept But why not use interfaces? Does this defeat the purpose of the pattern some how? Why not implement a new visitor that implements a new functionality (a new visit method)? Would this C# example not be considered an implementation of the visitor pattern? If not, why not?
interface IAcceptor
{
string Name { get; }
void Accept(IVisitor visitor);
}
interface IVisitor
{
void Visit(IAcceptor acceptor);
}
class AcceptorA : IAcceptor
{
public string Name => "ACCEPTOR A";
public void Accept(IVisitor visitor)
{
visitor.Visit(this);
}
}
class AcceptorB : IAcceptor
{
public string Name => "ACCEPTOR B";
public void Accept(IVisitor visitor)
{
visitor.Visit(this);
}
}
class VisitorA : IVisitor
{
public void Visit(IAcceptor acceptor)
{
Console.WriteLine($"VISITOR A visiting {acceptor.Name}");
}
}
class VisitorB : IVisitor
{
public void Visit(IAcceptor acceptor)
{
Console.WriteLine($"VISITOR B visiting {acceptor.Name}");
}
}
Foo
andBar
are the "lingua franca" of example code. Yet many here seem to dislike them. Odd.