#format java /** * VisitorPattern example */ import java.util.Iterator; import java.util.Vector; abstract class Visitor { public abstract void visit(File file); public abstract void visit(Directory directory); } interface Acceptor { public abstract void accept(Visitor v); } abstract class Entry implements Acceptor { public abstract String getName(); public abstract int getSize(); public Entry add(Entry entry) throws FileTreatmentException { throw new FileTreatmentException(); } public Iterator iterator() throws FileTreatmentException { throw new FileTreatmentException(); } public String toString() { return getName() + " (" + getSize() + ")"; } } class File extends Entry { private String name; private int size; public File(String name, int size) { this.name = name; this.size = size; } public String getName() { return name; } public int getSize() { return size; } public void accept(Visitor v) { v.visit(this); } } class Directory extends Entry { private String name; private Vector dir = new Vector(); public Directory(String name) { this.name = name; } public String getName() { return name; } public int getSize() { int size = 0; Iterator it = dir.iterator(); while(it.hasNext()) { Entry entry = (Entry)it.next(); size += entry.getSize(); } return size; } public Entry add(Entry entry) { dir.add(entry); return this; } public Iterator iterator() { return dir.iterator(); } public void accept(Visitor v) { v.visit(this); } } class ListVisitor extends Visitor { private String currentdir = ""; public void visit(File file) { System.out.println(currentdir + "/" + file); } public void visit(Directory directory) { System.out.println(currentdir + "/" + directory); String savedir = currentdir; currentdir = currentdir + "/" + directory.getName(); Iterator it = directory.iterator(); while(it.hasNext()) { Entry entry = (Entry)it.next(); entry.accept(this); } currentdir = savedir; } } class FileTreatmentException extends RuntimeException { public FileTreatmentException() { } public FileTreatmentException(String msg) { super(msg); } } public class VisitorDirectory { public static void main(String[] args) { try { System.out.println("Making root entries..."); Directory root = new Directory("root"); Directory bin = new Directory("bin"); Directory usr = new Directory("usr"); root.add(bin); root.add(usr); bin.add(new File("vi",10000)); bin.add(new File("latex",20000)); root.accept(new ListVisitor()); } catch(FileTreatmentException e) { e.printStackTrace(); } } }