I am attempting to implement the Visitor design pattern. I have a basic understanding of the Visitor pattern and its classic implementation. I am attempting to morph the visitor pattern to meet my specific goal.
Specific Goal: Add a Return Type to the Visitor Pattern that is specific to which Visitable(node) is being visited.
The classic examples I've seen so far of a visitor returning a specific return type can be achived by generics. But this does not meet my goal: Add a Return Type to the Visitor Pattern that is specific to which Visitable(node) is being visited.
Here's the other SO questions I looked at before posting mine: Visitor Design Pattern - return type java - Return a value from Visitor
Implementing Visitor Pattern while allowing different return types of functions --> This question did offer a solution (ie store state inside the visitor, but I didn't love that the caller or consumer of the API would need to remember to get the state back out after calling visit.
Here's some code to show what I mean:
public interface IVisitor<TReturn>
{
TReturn Visit(VisitableClassReturnString visitableClass);
TReturn Visit(VisitibleClassReturnInt visitibleClass);
}
public class Visitor : IVisitor<string>
{
public string Visit(VisitableClassReturnString visitableClass)
{
// Return type is correct.
// Logic for visiting (just examples for a return typebelow)
return string.Empty;
}
public string Visit(VisitibleClassReturnInt visitibleClass)
{
// Return type is NOT correct.
// Logic for visiting (just examples for a return typebelow)
return 0;
}
}
As shown in the code above, I have two different Visitable Classes (nodes) that my visitor wants to visit, in my specific application when I visit those two nodes, I need to return a DIFFERENT type upon visit. Also important to note, that return types being different is only specific to this concrete implementation of Visitor, in all other cases of IVisitor being implmeted the nodes will all likley have the same return type.
That can't be achieved using the single generic, does anyone have any thoughts on how I can achieve my goal?
In the visitor pattern, all Elements are the same type. you can't change the return type based on the element type. When you visit a collection of elements, you expect that the result of each visit will return the same data type. You can't change the result type in the middle of the elements chain.