Compositeパターン
再帰。
% find . -name "*.java" -print0 |xargs -0 cat [] import java.util.ArrayList; import java.util.List; public class Directory extends Entory { private String name; private List<Entory> directory = new ArrayList<Entory>(); public Directory(String name) { this.name = name; } @Override public String getName() { return name; } @Override public int getSize() { int size = 0; for (Entory entry : directory) { size += entry.getSize(); } return size; } @Override public Entory add(Entory entory) { directory.add(entory); entory.parent = this; return this; } @Override protected void printLine(String prefix) { System.out.println(prefix + "/" + this); for (Entory entory : directory) { entory.printLine(prefix + "/" + name); } } } public abstract class Entory { protected Entory parent; public abstract String getName(); public abstract int getSize(); public Entory add(Entory entry) throws Exception { throw new Exception(""); } public void printLine() { printLine(""); } protected abstract void printLine(String prefix); @Override public String toString() { return getName() + "(" + getSize() + ")"; } public String getFullPath() { StringBuffer sb = new StringBuffer(); Entory entory = this; do { sb.insert(0, "/" + entory.getName()); entory = entory.parent; } while (entory != null); return sb.toString(); } } public class File extends Entory { private String name; private int size; public File(String name, int size) { this.name = name; this.size = size; } @Override public String getName() { return name; } @Override public int getSize() { return size; } @Override protected void printLine(String prefix) { System.out.println(prefix + "/" + this.toString()); } } public class Main { public static void main(String... args) throws Exception { Entory rootdir = new Directory("root"); Entory bindir = new Directory("bin"); Entory tmpdir = new Directory("tmp"); Entory usrdir = new Directory("usr"); Entory hanadir = new Directory("hanako"); rootdir.add(bindir); rootdir.add(tmpdir); rootdir.add(usrdir); usrdir.add(hanadir); bindir.add(new File("vi", 10000)); bindir.add(new File("emacs", 12000)); tmpdir.add(new File("tmp.txt", 300)); tmpdir.add(new File("hoge.txt", 3)); Entory superfile = new File("superfile.txt", 330); hanadir.add(superfile); rootdir.printLine(); System.out.println(superfile.getFullPath()); } }
/root(22633) /root/bin(22000) /root/bin/vi(10000) /root/bin/emacs(12000) /root/tmp(303) /root/tmp/tmp.txt(300) /root/tmp/hoge.txt(3) /root/usr(330) /root/usr/hanako(330) /root/usr/hanako/superfile.txt(330) /root/usr/hanako/superfile.txt