- 抽象构件角色
public abstract class Component {
public void doSomething() {
//具体处理或逻辑
}
//节点添加
public abstract void add(Component component) ;
//节点删除
public abstract void remove(Component component) ;
//获取子节点
public abstract List<Component> getChild();
}
- 树枝节点
public class Composite extends Component {
//整个树容器
private List<Component> componentList = new ArrayList<>();
//节点添加
@Override
public void add(Component component) {
this.componentList.add(component);
}
//节点删除
@Override
public void remove(Component component) {
this.componentList.remove(component);
}
//获取子节点
@Override
public List<Component> getChild() {
return this.componentList;
}
}
- 叶子节点
public class Leaf extends Component {
@Deprecated
@Override
public void add(Component component) {
throw new UnsupportedOperationException();
}
@Deprecated
@Override
public void remove(Component component) {
throw new UnsupportedOperationException();
}
@Deprecated
@Override
public List<Component> getChild() {
throw new UnsupportedOperationException();
}
}
- 树的创建及组装
Component root = new Composite();
Component composite = new Composite();
Component leaf = new Leaf();
root.add(composite);
composite.add(leaf);
- 树的遍历
private void display(Component root) {
for (Component component :
root.getChild()) {
if (component instanceof Leaf) {
component.doSomething();
} else {
display(component);
}
}
}