Visitor

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.

FileVisitor.java

public interface FileVisitor {
    void visitFile(File parent, File file);
}

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.

java/design_patterns/visitor.txt · Last modified: 2010/08/12 by emilmont
CC Attribution-Noncommercial-Share Alike 3.0 Unported
Valid CSS Driven by DokuWiki Recent changes RSS feed Valid XHTML 1.0