dimanche 8 janvier 2017

Visitor vs Composition

As I see it visitor design pattern is very similar to the way composition work. In composition I would hold an interface member in the class and pass a concrete implementation of the interface in the constructor, and then either delegate a method to it or use it inside the class.

In visitor design pattern I also have a concrete implementation of the interface, and I send it to the visit method which then delegates the visit method to it.

To show this similarity in code, a visitor would be:

VisitorInterface v = new ConcreteVisitor();
MyClass c = new MyClass();
c.visit(v);
VisitorInterface dv = new DifferentVisitor();
c.visit(dv);

And composition would be:

SomeInterface i = new ConcreteImplementation();
MyClass c = new MyClass(i);
c.visit();  // called visit just to show the symmetry to visitor pattern
SomeInterface di = new DifferentImplementation();
c.changeReference(di);
c.visit(); 

I would like to hear your thoughts as to in which cases you would prefer one over the other and why

Aucun commentaire:

Enregistrer un commentaire