Here's the context/sample code of visitor design pattern.
public interface Visitable{
public void accept(Visitor v);
}
public class Book implements Visitable{
public void accept(Visitor v){
v.visit(this);
}
public void read() {}
/**
book stuff
**/
}
public class Movie implements Visitable{
public void accept(Visitor v){
v.visit(this);
}
public void watch() {}
/**
movie stuff
**/
}
public interface Visitor{
public void visit(Book b);
public void visit(Movie m);
}
public class Person implements Visitor{
public void visit(Book b){
b.read();
}
public void visit(Movie m){
m.watch();
}
}
My instructor says that it's no a good idea to overload visit
method and I should give a distinct name to each visit method that looks like the following. I'm not convinced by this idea. Can someone explain what's the downside of overloading visit
method?
public interface Visitor{
public void visitBook(Book b);
public void visitMovie(Movie m);
}
public class Person implements Visitor{
public void visitBook(Book b){
b.read();
}
public void visitMovie(Movie m){
m.watch();
}
}
The visitor pattern consists of two parts: a method called Visit() which is implemented by the visitor and is called for every element in the data structure. visitable classes providing Accept() methods that accept a visitor.
The Visitor pattern represents an operation to be performed on the elements of an object structure without changing the classes on which it operates. This pattern can be observed in the operation of a taxi company. When a person calls a taxi company (accepting a visitor), the company dispatches a cab to the customer.
In object-oriented programming and software engineering, the visitor design pattern is a way of separating an algorithm from an object structure on which it operates. A practical result of this separation is the ability to add new operations to existing object structures without modifying the structures.
The Visitor pattern suggests that you place the new behavior into a separate class called visitor, instead of trying to integrate it into existing classes.
John Vlissides's book Pattern Hatching (one of the GOF authors and his book is sometimes considered a supplement to Design Patterns) explains the advantages both both ways to implement Visitor.
The reason he says using the different variable names is this:
A more substantial advantage comes when there's a resonalbe default behavior, and subclasses tend to override just a few of the operations. When we overload, subclasses must override all of the functions; otherwise your friendly C++ compiler will probably complain that your selective overrides hide one or more of the base class operations. We get around this probelm when we give Visitor operations difference names. Subclasses can then redefine a subset of the operations with impunity. - Pattern Hatching p.36
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With