문제

When implementing the Visitor Pattern, is it a bad idea to add additional parameters to the Accept and Visit methods? I have never seen any examples that do this but no mention of it being a bad idea either.

I would like to use this pattern in my domain model however additional parameters are required along with the entity itself.

eg -

public interface ISomethingVisitor
{
    void Visit(Foo foo, int p1, int p2);
}

public interface ISomethingVisitable
{
    void Accept(ISomethingVisitor visitor, int p1, int p2);
}
도움이 되었습니까?

해결책

I'd say it's a bad idea. It might work fine for this visitor, but what happens when another visitor requires more/different parameters? If p1, p2 don't change, you can give them to the visitor at construction:

public class MyVisitor : ISomethingVisitor
{
    private int p1;
    private int p2;

    public MyVisitor(int p1, int p2)
    {
       _p1 = p1;
       _p2 = p2;
    }

    public void Visit(Foo foo)
    {
        //got access to _p1, _p2 here 
    }
}

다른 팁

I'm doing something similar to this, but with Java. I'm facing the same issue where I want to pass some 'visit context' information to the visit, but my issue is that the 'Visitor' is stateless so only one visitor is created up front to service all threads (ie: all information will have to come through paramaters). I don't want to get into the business of thread local vars.

So, to the design of your interface, I'd suggest the following:

public interface ISomethingVisitor
{
    void Visit(Foo foo, VisitOptions params);
}

public interface ISomethingVisitable
{
    void Accept(ISomethingVisitor visitor, VisitOptions params);
}

In this way, you can define your VisitOptions params with 2 fields: p1 and p2, and if you want to add some paramaters later, no problem by adding those to your VisitOptions class...any existing code will just ignore they exist. You run into problems if you modify the VisitOptions by changing/removing parameters, but that's typical backwards-compatibility concerns.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top