UML
根节点
public abstract class Component {
protected String name;
public Component(String name) {
this.name = name;
}
public abstract void add(Component component);
public abstract void remove(Component component);
public abstract void disPlay(int depth);
public String getDepth(int depth) {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < depth; i++) {
stringBuilder.append('-');
}
return stringBuilder.toString();
}
}
叶子节点
public class Leaf extends Component {
public Leaf(String name) {
super(name);
}
@Override
public void add(Component component) {
System.out.println("树叶节点无法添加子节点!");
}
@Override
public void remove(Component component) {
System.out.println("树叶节点无法删除子节点!");
}
@Override
public void disPlay(int depth) {
System.out.println(getDepth(depth) + name);
}
}
枝节点
import java.util.ArrayList;
import java.util.List;
public class Composite extends Component {
private List<Component> tree = new ArrayList<>();
public Composite(String name) {
super(name);
}
@Override
public void add(Component component) {
tree.add(component);
}
@Override
public void remove(Component component) {
tree.remove(component);
}
@Override
public void disPlay(int depth) {
System.out.println(getDepth(depth) + name);
for (Component component : tree) {
component.disPlay(depth + 2);
}
}
}
测试类
public class Main {
public static void main(String[] args) {
Component root = new Composite("Root");
root.add(new Leaf("叶子—1"));
root.add(new Leaf("叶子—2"));
root.add(new Leaf("叶子—3"));
Component component = new Composite("树枝—1");
component.add(new Leaf("叶子—1"));
component.add(new Leaf("叶子—2"));
component.add(new Leaf("叶子—3"));
Composite composite = new Composite("树枝—1—1");
composite.add(new Leaf("叶子—1"));
composite.add(new Leaf("叶子—2"));
composite.add(new Leaf("叶子—3"));
component.add(composite);
root.add(component);
root.disPlay(1);
}
}
输出结果