概念:将对象组合成树形结构以表示“部分——整体”的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性
核心:需求中是提现部分与整体层次的结构时,整体与部分可以一致对待。
操作树关系图
组合模式结构图
java代码:
public class CompositeTest {
public static void main(String[] args) {
Component root = new Composite("根节点");
Component leaf1 = new Leaf("根节点叶子节点1");
Component leaf2 = new Leaf("根节点叶子节点2");
root.Add(leaf1);
root.Add(leaf2);
Component composite = new Composite("根节点组合节点1");
root.Add(composite);
Component leaf3 = new Leaf("根节点叶子节点3");
Component leaf4 = new Leaf("根节点叶子节点4");
composite.Add(leaf3);
composite.Add(leaf4);
root.Display(0);
}
}
//叶子节点和叶节点的抽象类
public abstract class Component {
String name;
public Component(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public abstract void Add(Component component);
public abstract void Remove(Component component);
public abstract void Display(int depth);
}
//叶节点
public class Composite extends Component {
List<Component> list = new ArrayList<>();
public Composite(String name) {
super(name);
}
@Override
public void Add(Component component) {
list.add(component);
}
@Override
public void Remove(Component component) {
list.remove(component);
}
@Override
public void Display(int depth) {
for (int i = 0 ; i <= depth ; i ++){
System.out.print("-");
}
System.out.println(name);
for (Component component : list) {
component.Display(depth + 2);
}
}
}
//叶子节点
public class Leaf extends Component {
public Leaf(String name) {
super(name);
}
@Override
public void Add(Component component) {
System.out.println("can not add by leaf");
}
@Override
public void Remove(Component component) {
System.out.println("can not remove by leaf");
}
@Override
public void Display(int depth) {
for (int i = 0 ; i <= depth ; i ++){
System.out.print("-");
}
System.out.println(name);
}
}