坦克大战(一期)-设计模式-组合composite(树状结构专用模式)

DesignPatterns
bingor 2 years ago
parent a31873c566
commit 9e1e86d93a

@ -0,0 +1,40 @@
package com.msb.composite;/**
* @Author bingor
* @Date 2022/10/14 18:49
* @Description: com.msb.composite
* @Version: 1.0
*/
import java.util.ArrayList;
import java.util.List;
/**
*@ClassName BranchNode
*@Description TODO
*@Author bingor
*@Date 2022/10/14 18:49
*@Version 3.0
*/
public class BranchNode extends Node {
private String name;
private List<Node> nodes = new ArrayList<>();
public BranchNode(String name) {
this.name = name;
}
@Override
public void print() {
System.out.println(this.name);
}
public void addNode(Node node) {
nodes.add(node);
}
public List<Node> getNodes() {
return this.nodes;
}
}

@ -0,0 +1,27 @@
package com.msb.composite;/**
* @Author bingor
* @Date 2022/10/14 16:22
* @Description: com.msb.composite
* @Version: 1.0
*/
/**
*@ClassName LeafNode
*@Description TODO
*@Author bingor
*@Date 2022/10/14 16:22
*@Version 3.0
*/
public class LeafNode extends Node {
private String content;
public LeafNode(String content) {
this.content = content;
}
@Override
public void print() {
System.out.println(this.content);
}
}

@ -0,0 +1,50 @@
package com.msb.composite;/**
* @Author bingor
* @Date 2022/10/14 18:54
* @Description: com.msb.composite
* @Version: 1.0
*/
/**
*@ClassName Main
*@Description TODO
*@Author bingor
*@Date 2022/10/14 18:54
*@Version 3.0
*/
public class Main {
public static void main(String[] args) {
BranchNode root = new BranchNode("root");
BranchNode chapter1 = new BranchNode("chapter1");
BranchNode chapter2 = new BranchNode("chapter2");
LeafNode c11 = new LeafNode("c11");
LeafNode c12 = new LeafNode("c12");
BranchNode c2b1 = new BranchNode("c2b1");
LeafNode c2b11 = new LeafNode("c2b11");
LeafNode c2b12 = new LeafNode("c2b12");
root.addNode(chapter1);
root.addNode(chapter2);
chapter1.addNode(c11);
chapter1.addNode(c12);
chapter2.addNode(c2b1);
c2b1.addNode(c2b11);
c2b1.addNode(c2b12);
tree(root, 0);
}
private static void tree(Node root, int depth) {
for (int i=0; i<depth; i++) {
System.out.print("--");
}
root.print();
if(root instanceof BranchNode) {
for(Node node : ((BranchNode) root).getNodes()) {
tree(node, depth+1);
}
}
}
}

@ -0,0 +1,17 @@
package com.msb.composite;/**
* @Author bingor
* @Date 2022/10/14 16:22
* @Description: com.msb.composite
* @Version: 1.0
*/
/**
*@ClassName Node
*@Description TODO
*@Author bingor
*@Date 2022/10/14 16:22
*@Version 3.0
*/
public abstract class Node {
public abstract void print();
}
Loading…
Cancel
Save