组合模式

Composite 组合模式#

树状结构专用模式

 

复制代码
abstract class Node{
    abstract public void p();
}

class leafNode extendx Node{
    String content;
    public leafNode(String content){
        this.content = content;
    }
    
    public void p(){
        System.out.println(content);
    }
}

class BranchNode extends Node{
    List<Node> nodes = new ArrayList<>();
    String name;
    public BranchNode(String name){
        this.name = name;
    }
}

public class Main{
    public static void main(){
        BranchNode root = new BranchNode('root');
        BranchNode chapter1 = new BranchNode("chapter1");
        BranchNode chapter2 = new BranchNode("chapter2");
        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);
        root.add(chapter2);
        chapter1.add(cl1);
        chapter2.add(cl2);
        b21.add(c211);
        b21.add(c212);

        tree(root);
    }    
    static void tree(Node b, int depth){
        for(int i = 0; i < depth; i++){
            System.out.println("--");
        }
        b.p();
        if(b instanceof BranchNode){
            for(Node n : ((BranchNode)b).nodes){
                tree(n, depth + 1);
            }
        }
    }
}
复制代码

 

posted @   BigBender  阅读(45)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
历史上的今天:
2020-01-10 编译原理(清华大学出版社)-- 文法和语言 -- 上下文无关文法及其语法树
2020-01-10 编译原理(清华大学出版社)-- 文法和语言 -- 文法和语言的形式定义
2020-01-10 编译原理(清华大学出版社)-- 文法和语言 -- 文法的类型
点击右上角即可分享
微信分享提示
主题色彩