3
votes

In the visitor pattern, i want the client to only have access to the getters of the elements, while the visitors should have access to getters and setters. How would you implement it?

I don't want the visitors in the same package as the model (there are a lot of classes already). I was thinking about introducing IWriteable interface which contains setters and accept methods. Is there a better way?

enter image description here

Thanks

1
Your initial thought: two interfaces Client (readonly) and Visitor(read/write) is the canonical way to go. - CPerkins
The number of classes is no reason for putting them into a package or not. The question is where does it belong to logically. I would always put a visitor that is traversing a model into the model package. However CPerkins is right, two interfaces is the most straight forward approach, but does not save you from a rogue programmer casting back and forth, e.g. - Angel O'Sphere
Thanks CPerkins and Angel for your replies. - user802421

1 Answers

0
votes

@Angel O'Sphere:

The package would contains models, visitors and factories all that ~2x (interfaces and impls). I had some thought about rogue programmer too, that's why I asked. Another approach would be:

public class ModelImpl implement IRead {
  @Override
  public Foo getFoo() {...}

  private void setFoo(Foo f) {...}

  public void accept(Visitor v) {
    v.visit(new ModelEditor());
  }

  private class ModelEditor implement IWrite {
    @Override
    public void setFoo(Foo f) {
      ModelImpl.this.setFoo(f);
    }
  }
}

But this approach has many drawbacks and is cumbersome without generative techniques :o