For implementing a Visitor Pattern in Java you can use Overriding or Overloading. Does the choice depends or is it always preferable to choose one of the two? Because I don't see no disadvantages. Because I think the first and third example will always do the job?
Visitor with overriding
public interface Visitor {
public void visitX(X x);
public void visitY(Y y);
}
public class ConcreteVisitor {
public void visitX(X x) { ... }
public void visitY(Y y) { ... }
}
public abstract class XY {
public abstract void accept(Visitor v);
}
public class X extends XY {
// alternative: one implementation with reflection possible in super class
public void accept(Visitor v) {
v.visitX(this);
}
}
public class Y extends XY {
// alternative: one implementation with reflection possible in super class
public void accept(Visitor v) {
v.visitY(this);
}
}
Visitor with overloading
public interface Visitor {
public void visit(XY xy); // dummy (couldn't otherwise been used in XY class)
public void visit(X x);
public void visit(Y y);
}
public class ConcreteVisitor {
public void visit(XY xy) { ... }
public void visit(X x) { ... }
public void visit(Y y) { ... }
}
public abstract class XY {
public void accept(Visitor v) {
v.visit(this); // Which is the compile-time/static type of this? XY?
}
}
public class X extends XY {
}
public class Y extends XY {
}
Better Visitor with overloading
public interface Visitor {
public void visit(X x);
public void visit(Y y);
}
public class ConcreteVisitor {
public void visit(X x) { ... }
public void visit(Y y) { ... }
}
public abstract class XY {
public abstract void accept(Visitor v);
}
public class X extends XY {
public void accept(Visitor v) {
v.visit(this);
}
}
public class Y extends XY {
public void accept(Visitor v) {
v.visit(this);
}
}