Properties:
- Used when it is necessary to execute actions on members of an object structure (e.g. collections, hierarchical structures, composite structures).
- Separates algorithm of the actions from the object structure members. So that new algorithms can be modified easily.
- Another advantage is that visitor objects may be statefull.
- One disadvantages is, while it is easy to add new visitors, it is difficult to add new observable objects.
Implementation:
- Visitor interface declares visit methods. For each ConcreteVisitable object a separate overridden visit method should be declared.
- ConcreteVisitor implements visitor.
- Visitable interface declares the accept method to which visitor instance is passed.
- ConcreteVisitable implements visitable interface and defines accept method which executes the visitor.
- ObjectStructure contains visitable objects. Visitable objects are iterated and visitor is passed.
- Double Dispatch: Refers to how visit method to invoke is selected. First dispatch is selecting the accept method, which is determined by static type of visitor and dynamic type of visitable. Second dispatch is selecting the visit method, which is determined by dynamic type of visitor and static type of visitable.
Java Standard Library Implementations:
- java.nio.file.FileVisitor
- javax.lang.model.element.AnnotationValueVisitor
- javax.lang.model.type.TypeVisitor
Example Usage:
Path start = Paths.get(".");
Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException
{
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException e)
throws IOException
{
if (e == null) {
Files.delete(dir);
return FileVisitResult.CONTINUE;
} else {
// directory iteration failed
throw e;
}
}
});
Comments
Post a Comment