組合模式node
public class Node { private String id; private String name; private String parentId; private List<Node> children = new ArrayList<>(); public Node(String id, String name, String parentId) { this.id = id; this.name = name; this.parentId = parentId; } //getter,setter方法 public void add(Node node){ List<Node> nodeList = this.getChildren(); nodeList.add(node); this.setChildren(nodeList); } public void print(){ System.out.println("node:" + getName()); for(Node node : children){ node.print(); } } }
public static void main(String[] args) { Node node = new Node("1", "root", ""); Node node1 = new Node("2", "composite1", "1"); Node node2 = new Node("3", "leaf1", "1"); Node node3 = new Node("4", "leaf2", "2"); node1.add(node3); node.add(node1); node.add(node2); node.print(); }
node:root node:composite1 node:leaf2 node:leaf1
https://github.com/Seasons20/DisignPattern.git
ENDgit