组合模式- 2020-12-02 22:54- 设计模式
demo
/**
* 节点
*
* @author Bai
* @date 2020/12/2 22:30
*/
@Data
public class Node {
/**
* 节点名称
*/
private String name;
public Node(String name) {
this.name = name;
}
}
/**
* @author Bai
* @date 2020/12/2 22:31
*/
public class BranchNode extends Node {
public BranchNode(String name) {
super(name);
}
/**
* 子节点
*/
private List<Node> childNodes = new ArrayList<>();
public BranchNode add(Node node) {
childNodes.add(node);
return this;
}
public List<Node> getChildNodes() {
return childNodes;
}
public void setChildNodes(List<Node> childNodes) {
this.childNodes = childNodes;
}
}
@Test
public void demo() {
//模拟一次 目录路径, 并且打印出 从根目录到子目录的 所有路径
//根节点
BranchNode root = new BranchNode("root");
//根节点下有两个子级目录 chapter1 chapter2
BranchNode chapter1 = new BranchNode("chapter1");
//chapter1 下有两个子级目录
BranchNode chapter1_1 = new BranchNode("chapter1_1");
//chapter1_1下有一个子级
Node chapter1_1_1 = new Node("chapter1_1_1");
chapter1_1.add(chapter1_1_1);
//chapter1_2为叶子目录
Node chapter1_2 = new Node("chapter1_2");
chapter1.add(chapter1_1).add(chapter1_2);
//chapter2 下有三个子级目录
BranchNode chapter2 = new BranchNode("chapter2");
//chapter2 下有两个子级目录
BranchNode chapter2_1 = new BranchNode("chapter2_1");
//chapter2_1 下有一个子级
Node chapter2_1_1 = new Node("chapter2_1_1");
chapter2_1.add(chapter2_1_1);
//chapter1_2为叶子目录
Node chapter2_2 = new Node("chapter1_2");
Node chapter2_3 = new Node("chapter2_3");
chapter2.add(chapter2_1).add(chapter2_2).add(chapter2_3);
root.add(chapter1);
root.add(chapter2);
//递归打印出来每个节点
print(root, 0);
}
private void print(Node root, int depth) {
for (int i = 0; i < depth; i++) {
System.out.print("——");
}
System.out.println(root.getName());
if (root instanceof BranchNode) {
BranchNode branchNode = (BranchNode) root;
for (Node childNode : branchNode.getChildNodes()) {
print(childNode, depth + 1);
}
}
}
**
root
——chapter1
————chapter1_1
——————chapter1_1_1
————chapter1_2
——chapter2
————chapter2_1
——————chapter2_1_1
————chapter1_2
————chapter2_3
**