簡要說明
文章來源:http://www.zghlxwxcb.cn/news/detail-800297.html
一、代碼實(shí)現(xiàn)
- 定義抽象節(jié)點(diǎn)類
Node
,定義抽象方法public abstract void print();
- 定義葉子節(jié)點(diǎn)類
LeafNode
,繼承Node節(jié)點(diǎn),實(shí)現(xiàn)print()
抽象方法,葉子節(jié)點(diǎn)沒有子節(jié)點(diǎn)- 定義子節(jié)點(diǎn)類
BranchNode
,繼承Node節(jié)點(diǎn),實(shí)現(xiàn)print()
抽象方法,子節(jié)點(diǎn)既可以有子節(jié)點(diǎn),也又可以有葉子節(jié)點(diǎn)- 定義一個(gè)樹狀目錄結(jié)構(gòu),使用遞歸打印樹狀目錄結(jié)構(gòu)
import java.util.ArrayList;
import java.util.List;
/**
* @description: composite組合模式
* @author: flygo
* @time: 2022/7/20 14:05
*/
public class CompositeMain {
public static void main(String[] args) {
BranchNode root = new BranchNode("root");
BranchNode chapter1 = new BranchNode("chapter1");
BranchNode chapter2 = new BranchNode("chapter2");
Node r1 = new LeafNode("r1");
Node c11 = new LeafNode("c11");
Node c12 = new LeafNode("c12");
BranchNode b21 = new BranchNode("section21");
Node c211 = new LeafNode("c211");
Node c212 = new LeafNode("c212");
root.add(chapter1).add(chapter2).add(r1);
chapter1.add(c11).add(c12);
chapter2.add(b21);
b21.add(c211).add(c212);
tree(root, 0);
}
private static void tree(Node node, int depth) {
for (int i = 0; i < depth; i++) {
System.out.print("--");
}
node.print();
if (node instanceof BranchNode) {
for (Node n : ((BranchNode) node).nodes) {
tree(n, depth + 1);
}
}
}
}
abstract class Node {
public abstract void print();
}
/**
* @description: 葉子節(jié)點(diǎn)-不能有子節(jié)點(diǎn)
* @author: flygo
* @time: 2022/7/20 14:10
*/
class LeafNode extends Node {
String content;
public LeafNode(String content) {
this.content = content;
}
@Override
public void print() {
System.out.println(content);
}
}
/**
* @description: 子節(jié)點(diǎn)-可以有子節(jié)點(diǎn)和葉子節(jié)點(diǎn)
* @author: flygo
* @time: 2022/7/20 14:10
*/
class BranchNode extends Node {
// 子節(jié)點(diǎn)可以有子節(jié)點(diǎn)和葉子節(jié)點(diǎn)
List<Node> nodes = new ArrayList<>();
String name;
public BranchNode(String name) {
this.name = name;
}
@Override
public void print() {
System.out.println(name);
}
public BranchNode add(Node node) {
this.nodes.add(node);
return this;
}
}
二、源碼地址
https://github.com/jxaufang168/Design-Patternshttps://github.com/jxaufang168/Design-Patterns文章來源地址http://www.zghlxwxcb.cn/news/detail-800297.html
到了這里,關(guān)于【設(shè)計(jì)模式-07】Composite組合模式的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!