一、适用场景:表示对象的【整体–部分】树形层次结构,同时忽略单个对象和组合对象的差异。比如一颗树,是由分支节点和叶子结点组成的层次结构,同时,我们希望给用户提供统一的接口对结点进行操作,不论是分支结点还是叶子结点
二、示例。
1.定义抽象的结点类:

package cn.edu.tju.app;

public abstract class TreeNode {
private String content;

public String getContent() {
return content;
}

public void setContent(String content) {
this.content = content;
}

public abstract void print();
public abstract void addNode(TreeNode node);
}

2.定义两个类,分别继承上述抽象类,分别代表根结点和叶子结点

package cn.edu.tju.app;

import java.util.LinkedList;
import java.util.List;

public class TreeNodeBranch extends TreeNode {
private List<TreeNode> nodeList=new LinkedList<>();
@Override
public void print() {
System.out.println(this.getContent());
for(TreeNode treeNode:nodeList){
treeNode.print();
}
}

@Override
public void addNode(TreeNode node){
nodeList.add(node);
}
}
package cn.edu.tju.app;

public class TreeNodeLeaf extends TreeNode {
@Override
public void print() {
System.out.println(this.getContent());
}

@Override
public void addNode(TreeNode node){

}
}

3.定义测试类,构建树,所有的操作都统一使用抽象类TreeNode中定义的方法,这就屏蔽了分支结点和叶子结点的差异

package cn.edu.tju.app;

public class TreeNodeTest {
public static void main(String[] args) {
TreeNode root=new TreeNodeBranch();
root.setContent("root");

TreeNode firstLevelChild11=new TreeNodeBranch();
firstLevelChild11.setContent("child11");
TreeNode firstLevelChild12=new TreeNodeBranch();
firstLevelChild12.setContent("child12");

TreeNode secondLevelChild21=new TreeNodeLeaf();
secondLevelChild21.setContent("child21");
TreeNode secondLevelChild22=new TreeNodeLeaf();
secondLevelChild22.setContent("child22");
TreeNode secondLevelChild23=new TreeNodeLeaf();
secondLevelChild23.setContent("child23");
TreeNode secondLevelChild24=new TreeNodeLeaf();
secondLevelChild24.setContent("child24");

root.addNode(firstLevelChild11);
root.addNode(firstLevelChild12);

firstLevelChild11.addNode(secondLevelChild21);
firstLevelChild11.addNode(secondLevelChild22);
firstLevelChild12.addNode(secondLevelChild23);
firstLevelChild12.addNode(secondLevelChild24);

root.print();
}
}

4.运行结果:

设计模式:21-组合模式_ide