1 /**
   2  * CompositePattern example
   3  */
   4 
   5 import java.util.Iterator;
   6 import java.util.Vector;
   7 
   8 abstract class Entry {
   9     public abstract String getName();
  10     public abstract int getSize();
  11     public Entry add(Entry entry) throws FileTreatmentException {
  12         throw new FileTreatmentException();
  13     }
  14     public void printList() {
  15         printList("");
  16     }
  17     protected abstract void printList(String prefix);
  18     public String toString() {
  19         return getName()+" ("+getSize()+")";
  20     }
  21 }
  22 
  23 class File extends Entry {
  24     private String name;
  25     private int size;
  26     public File(String name, int size) {
  27         this.name = name;
  28         this.size = size;
  29     }
  30     public String getName() {
  31         return name;
  32     }
  33     public int getSize() {
  34         return size;
  35     }
  36     protected void printList(String prefix) {
  37         System.out.println(prefix+"/"+this);
  38     }
  39 }
  40 
  41 class Directory extends Entry {
  42     private String name;
  43     private Vector directory = new Vector();
  44     public Directory(String name) {
  45         this.name = name;
  46     }
  47     public String getName() {
  48         return name;
  49     }
  50     public int getSize() {
  51         int size = 0;
  52         Iterator it = directory.iterator();
  53         while(it.hasNext()) {
  54             Entry entry = (Entry)it.next();
  55             size+=entry.getSize();
  56         }
  57         return size;
  58     }
  59     public Entry add(Entry entry) {
  60         directory.add(entry);
  61         return this;
  62     }
  63     protected void printList(String prefix) {
  64         System.out.println(prefix+"/"+this);
  65         Iterator it = directory.iterator();
  66         while(it.hasNext()) {
  67             Entry entry = (Entry)it.next();
  68             entry.printList(prefix+"/"+name);
  69         }
  70     }
  71 }
  72 
  73 class FileTreatmentException extends RuntimeException {
  74     public FileTreatmentException() {
  75     }
  76     public FileTreatmentException(String msg) {
  77         super(msg);
  78     }
  79 }
  80 
  81 public class CompositeDirectory {
  82     public static void main(String[] args) {
  83         try {
  84             System.out.println("Making root entries...");
  85             Directory root = new Directory("root");
  86             Directory bin = new Directory("bin");
  87             Directory usr = new Directory("usr");
  88             root.add(bin);
  89             root.add(usr);
  90             bin.add(new File("vi", 10000));
  91             bin.add(new File("latex", 20000));
  92             root.printList();
  93         } catch(FileTreatmentException e) {
  94             e.printStackTrace();
  95         }
  96     }
  97 }
web biohackers.net