Java Reference
In-Depth Information
@Override
public void visit(NonFictionBook book) {
nonFictionBooks.add(book);
}
public List<AudioBook> getAudioBooks() {
return audioBooks;
}
public List<FictionBook> getFictionBooks() {
return fictionBooks;
}
public List<NonFictionBook> getNonFictionBooks() {
return nonFictionBooks;
}
}
The main program code now becomes a simple and elegant affair:
public class VisitorTest {
public static void main(String[] args) {
Book[] books = new Book[]{
new AudioBook(), new FictionBook(), new FictionBook(),
new NonFictionBook(), new AudioBook(), new NonFictionBook()
};
CategorizingBookVisitor visitor = new CategorizingBookVisitor();
for (Book book : books)
book.accept(visitor); // Accept the visitor
System.out.println("Nr. audio books: "+visitor.getAudioBooks().size());
System.out.println("Nr. fiction books: "+visitor.getFictionBooks().size());
System.out.println("Nr. non-fiction books:
"+visitor.getNonFictionBooks().size());
}
}
The workings of the visitor pattern should be pretty clear by now. Consider the visitor to be an
object ringing a doorbell at another object's house. By calling the accept method, the object opens
the door and lets the visitor in.
template Method Pattern
The last two patterns to be discussed are easy to understand and make you think, “Of course,
this definitely seems like the normal way to do this.” Nevertheless, it is worthwhile to explic-
itly discuss them, because they are easy to overlook in practice if you haven't encountered them
before.
The template method pattern defines a general structure of a piece of code in a so‐called template
method, where some particular steps are kept abstract, left to the concrete subclasses to implement.
This pattern is particularly useful when you know the general structure of a piece of code, but want
to keep the internals flexible.
 
Search WWH ::




Custom Search