Composite pattern
入れ物と中身を同一視するパターン.
import std.stdio; interface Element { uint countChilds(); void append(Element c); } class Folder : Element { private Element[] elems; override uint countChilds() { uint sum; foreach (c; elems) { sum += 1 + c.countChilds(); } return sum; } override void append(Element c) { elems ~= c; } } class File : Element { override uint countChilds() { return 0; } override void append(Element c) { throw new Exception("Append error."); } } void main() { Element w = new Folder; // 集合体 Element x = new Folder; // 集合体 Element y = new File; // 要素 Element z = new File; // 要素 w.append(x); x.append(y); x.append(z); writeNumChilds(w); writeNumChilds(x); writeNumChilds(y); writeNumChilds(z); } void writeNumChilds(Element c) { writeln(c, " ", c.countChilds()); } a.Folder 3 a.Folder 2 a.File 0 a.File 0