public abstract class Component {
protected String name;
public Component(String name) {
this.name = name;
}
public abstract void add(Component c);
public abstract void traverse(int depth);
}
public class Leaf extends Component {
public Leaf(String name) {
super(name);
}
@Override
public void add(Component c) {
throw new UnsupportedOperationException("This operation is not supported.");
}
@Override
public void traverse(int depth) {
String s = "";
for (int i = 0; i < depth; i++) {
s += "-------";
}
System.out.println(s + name);
}
}
import java.util.ArrayList;
import java.util.List;
public class Composite extends Component {
private List<Component> children;
public Composite(String name) {
super(name);
children = new ArrayList<Component>();
}
@Override
public void add(Component c) {
children.add(c);
}
@Override
public void traverse(int depth) {
String s = "";
for (int i = 0; i < depth; i++) {
s += "-------";
}
System.out.println(s + name);
for (Component child : children) {
child.traverse(depth + 1);
}
}
}