I am revising the Visitor pattern I used some time ago. We have base class Element which has virtual method accept(Visitor) and this method is overridden in all classes inheriting from Element. And all that accept() does in any derived class is to call visitor->visit(*this). Now when the client runs the code, he/she does for example:
Visitor& theVisitor = *new ConcreteVisitor();
for_each(elements.begin(), elements.end(), [](Element& e) { e.accept(theVisitor));})
Why the client cannot just call visitor->visit(element) like this:
Visitor& theVisitor = *new ConcreteVisitor();
for_each(elements.begin(), elements.end(), [&theVisitor](Element& e) { theVisitor.visit(e); });
What useful information is in calling element.accept(visitor) which in turns calls visitor.visit(element)? This makes the usage of the Visitor pattern cumbersome and requires extra code in all the hierarchy of Element classes.
So can someone explain benefits of accept() here?
Aucun commentaire:
Enregistrer un commentaire