Intent: Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.
A common use case is a directory walker, with a related file visitor.
It is important to add the parent, not only the file itself, to be able to reconstruct the directories hierarchy.
DirectoryWalker.java
public class DirectoryWalker { private final File startingDirectory; public DirectoryWalker(final String startingDirectoryName) { this.startingDirectory = new File(startingDirectoryName); } public void walk(FileFilter filter, FileVisitor visitor) { final LinkedList<File> pendingDirectories = new LinkedList<File>(); visitor.visitFile(null, startingDirectory); pendingDirectories.add(startingDirectory); while (pendingDirectories.isEmpty() == false) { File parent = pendingDirectories.removeFirst(); File[] fileList = parent.listFiles(filter); Arrays.sort(fileList); for (File file : fileList) { visitor.visitFile(parent, file); if (file.isDirectory()) pendingDirectories.add(file); } } } }
The FileFilter allow to filter the file visited and Arrays.sort(fileList) allow to preserve the names ordering of the files.
visitor.visitFile(parent, file) is the call to the visitor.