I have two Visitor classes in my code Visitor1 and Visitor2 that execute functions on the classes ElementA and ElementB (both implement the interface Visitable that defines accept(Visitor)).
I do not want to support calling visit from Visitor1 on ElementB.
I thought of two different ways:
- Throw an exception when
Visitor1.visit(ElementB)is called:
public class Visitor1 extends Visitor {
@Override
public void visit(ElementA element) {
//...
}
@Override
public void visit(ElementB element) {
throw new UnsupportedOperationException();
}
}
- Implement two different Visitor classes and one
acceptmethod per visitor:
public ElementA implements Visitable1, Visitable 2 {
public void accept(Visitor1 v) {
//...
}
public void accept(Visitor2 v) {
//...
}
}
public ElementB implements Visitable2 {
public void accept(Visitor2 v) {
//...
}
}
How should I implement this the best? The first solution contradicts the Interface Segregation Principle and the second solution contradicts the visitor pattern, as the visitors cannot be as easily extendable.
visit(ElementB element)as a no-op (similar to null object pattern)? Perhaps that makes sense, and it could make things simpler? 2/2