Java Reference
In-Depth Information
visitor.visit(this);
}
}
public class AudioBook extends Book {
@Override
public void accept(BookVisitor visitor) {
visitor.visit(this);
}
}
public class NonFictionBook extends Book {
@Override
public void accept(BookVisitor visitor) {
visitor.visit(this);
}
}
You might be thinking there is no difference between this and the previous strategy, since both
require you to override the accept methods. However, since the concrete class extends the abstract
class, Eclipse will throw a warning in case you forget to implement this method in your new con-
crete class, and consequently will throw a warning to implement this in your interface as well. In
short, there's no risk of forgetting anything in this case.
Finally, you need to define the visitor implementation:
import java.util.ArrayList;
import java.util.List;
public class CategorizingBookVisitor implements BookVisitor {
private List<AudioBook> audioBooks;
private List<FictionBook> fictionBooks;
private List<NonFictionBook> nonFictionBooks;
public CategorizingBookVisitor() {
this.audioBooks = new ArrayList<>();
this.fictionBooks = new ArrayList<>();
this.nonFictionBooks = new ArrayList<>();
}
@Override
public void visit(AudioBook book) {
audioBooks.add(book);
}
@Override
public void visit(FictionBook book) {
fictionBooks.add(book);
}
Search WWH ::




Custom Search