CompositePattern

<textarea cols="50" rows="15" name="code" class="java">package CompositePattern; public abstract class Entry { public abstract String getName();//获取文件名 public abstract int getSize();//获取文件容量 public Entry add(Entry entry)throws FileThreatmentException{ //新增进入点 throw new FileThreatmentException(); } public void printList(){ //输出纵览 printList(&quot; &quot;); } protected abstract void printList(String prefix); //在前面加上Prefix后输出纵览 public String toString(){ return getName()+&quot;(&quot;+getSize()+&quot;)&quot;; } } </textarea> <textarea cols="50" rows="15" name="code" class="java">package CompositePattern; import java.util.Iterator; import java.util.Vector; public 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 = &quot;/&quot; + this); Iterator it = directory.iterator(); while(it.hasNext()){ Entry entry = (Entry)it.next(); entry.printList(prefix + &quot;/&quot; + name); } } } </textarea> <textarea cols="50" rows="15" name="code" class="java">package CompositePattern; public 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 this.name; } public int getSize(){ return size; } protected void printList(String prefix){ System.out.println(prefix + &quot;/&quot;+this); } } </textarea> <textarea cols="50" rows="15" name="code" class="java">package CompositePattern; public class FileThreatmentException extends RuntimeException{ public FileThreatmentException(){} public FileThreatmentException(String msg){ super(msg); } } </textarea> <textarea cols="50" rows="15" name="code" class="java">package CompositePattern; public class Main { public static void main(String[] args){ System.out.println(&quot;Making root entries...&quot;); Directory rootdir = new Directory(&quot;root&quot;); Directory bindir = new Directory(&quot;bin&quot;); Directory tmpdir = new Directory(&quot;tmp&quot;); Directory usrdir = new Directory(&quot;usr&quot;); rootdir.add(bindir); rootdir.add(tmpdir); rootdir.add(usrdir); bindir.add(new File(&quot;vi&quot;,10000)); bindir.add(new File(&quot;latex&quot;,10000)); rootdir.printList(); } } </textarea>

你可能感兴趣的:(CompositePattern)