Hello everybody,
Two patterns seem to be able to add functionality to a class, without modifying the class itself : the Decorator pattern and the Visitor pattern. I haven't really understood the difference between them two.
About the Visitor pattern : I hardly see the use of it when its visitants are well designed and it seems old-fashioned to me. Here's my test implementation :
Code:
class AbstractElement
{
public:
virtual void accept(AbstractVisitor v);
};
class AbstractVisitor
{
public:
virtual void visit(AbstractElement e);
};
class initVisitor : public AbstractVisitor
{
public:
void visit(AbstractElement e);
};
class productVisitor : public AbstractVisitor
{
public:
void visit(AbstractElement e);
};
now this implementation will not work :
Code:
void AbstractElement::accept(AbstractVisitor v)
{
v.visit(*this);
}
because "v" is an instantiation and not a pointer, so the dispatch by polymorphism fails. The functions "visit" and "accept" should hence take (smart) pointers (and thus the virtual functions can be purely virtual).
Now they say that separation between data and algorithms on that data can be established by the Visitor pattern, by simply adding a new visitor with the algorithm in the function "visit" :
Code:
void productVisitor::visit(AbstractElement e)
{
// .... the algorithm... but on what ?!
}
Now's my question : on what do we apply the algorithm? On data in the visited class ? But then we'll need to specify that data already in its interface class. So the class of visited objects should not have a polymorph base/interface? I mean, the class "AbstractElement" has no reason to be?
Thank you for your answer !!
Mark
edit: Since we'll need pointers to "AbstractVisitor" as argument in the function "accept", we'll need to instantiate the visitor classes somewhere. Then, if I've understood well, "accept" is a kind of call-back to the derived-class "visit" (by dispatch?).
Are the visitor objects not just a kind of function objects, passed as arguments in some function "do_something" ? This kind of call-back seems more modern to me...