UML
服装类
public abstract class Clothes {
protected String name;
public Clothes(String name) {
this.name = name;
}
public abstract void add(Object object);
public abstract void remove(Object object);
public abstract void display(int depth);
}
服装节点 可以保存服装节点或者叶子节点
import java.util.ArrayList;
import java.util.List;
public class Composite extends Clothes {
private List<Composite> clothes = new ArrayList<>();
private List<Leaf> leaves = new ArrayList<>();
public Composite(String name) {
super(name);
}
@Override
public void add(Object object) {
if (object instanceof Leaf) {
leaves.add((Leaf) object);
} else if (object instanceof Composite) {
clothes.add((Composite) object);
}
}
@Override
public void remove(Object object) {
if (object instanceof Leaf) {
leaves.remove(object);
} else if (object instanceof Composite) {
clothes.remove(object);
}
}
@Override
public void display(int depth) {
for (int i = 0; i < depth; i++) {
System.out.print(" ");
}
System.out.println("+" + name);
for (Leaf leaf : leaves) {
leaf.display(depth + 3);
}
for (Composite clothe : clothes) {
clothe.display(depth + 1);
}
}
}
叶子节点 无法保存其他节点
public class Leaf {
private String name;
public Leaf(String name) {
this.name = name;
}
public void display(int depth) {
for (int i = 0; i < depth; i++) {
System.out.print(" ");
}
System.out.println("-" + name);
}
}
测试类
public class Main {
public static void main(String[] args) {
Composite root = new Composite("服装");
Composite c1 = new Composite("男装");
c1.add(new Leaf("衬衫"));
c1.add(new Leaf("T恤"));
Composite c2 = new Composite("女装");
c2.add(new Leaf("连衣裙"));
c2.add(new Leaf("小花裙"));
root.add(c1);
root.add(c2);
root.display(0);
}
}
运行结果