Java Reference
In-Depth Information
};
return iterator;
}
}
}
Visitor Pattern
Just as with the chain‐of‐responsibility pattern you've seen before, the visitor pattern is a little
bit more advanced and its benefits might not immediately be clear when programming smaller
applications.
The main goal of a visitor pattern is to separate a certain algorithm (some code) from the data struc-
ture it operates on. Or, more practically speaking, the visitor pattern allows methods to be added to
a related set of classes without having to modify the classes themselves.
Again, let's dive immediately into an example. Let's say you're creating a book management system.
You decide to start from an abstract class and extend it to some concrete classes:
public abstract class Book {
private String title;
// ...
}
public class NonFictionBook extends Book {
// ...
}
public class FictionBook extends Book {
// ...
}
public class AudioBook extends Book {
// ...
}
So far, so good. Now let's say at some point you have a list of books you're keeping track of:
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()
};
}
}
Okay, now you want to sort this collection of books into three lists, one for each concrete class of
books. Simple, you think; you can just write the following:
import java.util.ArrayList;
import java.util.List;
 
Search WWH ::




Custom Search