#format java /** * CompositePattern example */ import java.util.Iterator; import java.util.Vector; abstract class Entry { public abstract String getName(); public abstract int getSize(); public Entry add(Entry entry) throws FileTreatmentException { throw new FileTreatmentException(); } public void printList() { printList(""); } protected abstract void printList(String prefix); 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; } protected void printList(String prefix) { System.out.println(prefix+"/"+this); } } class Directory extends Entry { private String name; private Vector directory = new Vector(); public Directory(String name) { this.name = name; } public String getName() { return name; } public int getSize() { int size = 0; Iterator it = directory.iterator(); while(it.hasNext()) { Entry entry = (Entry)it.next(); size+=entry.getSize(); } return size; } public Entry add(Entry entry) { directory.add(entry); return this; } protected void printList(String prefix) { System.out.println(prefix+"/"+this); Iterator it = directory.iterator(); while(it.hasNext()) { Entry entry = (Entry)it.next(); entry.printList(prefix+"/"+name); } } } class FileTreatmentException extends RuntimeException { public FileTreatmentException() { } public FileTreatmentException(String msg) { super(msg); } } public class CompositeDirectory { 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.printList(); } catch(FileTreatmentException e) { e.printStackTrace(); } } }