I'm looking at the explanation of the visitor pattern here which shows the following code:
public class ShoppingCart {
public double calculatePostage() {
PostageVisitor visitor = new PostageVisitor();
for(Visitable item: items) {
item.accept(visitor);
}
public class PostageVisitor implements Visitor {
public void visit(Book book) {
public class Book implements Visitable{
public void accept(Visitor vistor) {
visitor.visit(this);
}
From the standpoint of JavaScript developer the accept
method seems redundant since the code could be written like this:
for(Visitable item: items) {
// directly call visitor passing an item instead of doing so through `accept` method
visitor.visit(item);
}
Am I right to assume that this won't work because the compiler doesn't know which overloaded visit
method of the visitor to execute?
As I understand the compiler understands which visit
method to execute on the visitor
with accept
since it can match the type of this
passed to the visitor.visit(this)
method here:
public void accept(Visitor vistor) {
visitor.visit(this);
}
Edit:
Just found that in addition to the great answers here this answer also provides a lot of useful details.
ShoppingCart
implementVisitable
interface and the method is defined asvisit(Visitable)
on the visitor I wouldn't have any problems with the type mismatch during compilation? – Baynebridge