• JAVA设计模式之组合模式(composite)


    组合模式:树状结构专用模式

    代码如下:

    package com.srr.dp.composite;
    
    import java.util.ArrayList;
    import java.util.List;
    
    /**
     * 节点抽象
     */
    abstract class Node {
        private int id;
    
        public Node(int id){
            this.id = id;
        }
        /**
         * 打印
         */
        abstract public void print();
    }
    
    /**
     * 叶子节点
     */
    class LeafNode extends Node {
        String name;
        public LeafNode(int id,String name) {
            super(id);
            this.name = name;}
    
        @Override
        public void print() {
            System.out.println(name);
        }
    }
    
    /**
     * 分支节点
     */
    class BranchNode extends Node {
    
        List<Node> nodes = new ArrayList<>(); //分支节点下面还有分支节点或者叶子节点
        String path;
        String name;
    
        public BranchNode(int id,String name,String path) {
            super(id);
            this.name = name;
            this.path = path;
        }
    
        @Override
        public void print() {
            System.out.println(name);
        }
    
        public void add(Node n) {
            nodes.add(n);
        }
    }
    
    /**
     * 测试类
     */
    public class T {
        public static void main(String[] args) {
            BranchNode root = new BranchNode(0,"root","");
            BranchNode chapter1 = new BranchNode(1,"chapter1","");
            BranchNode chapter2 = new BranchNode(2,"chapter2","");
            Node r1 = new LeafNode(3,"r1");
            Node c11 = new LeafNode(4,"c11");
            Node c12 = new LeafNode(5,"c12");
            BranchNode b21 = new BranchNode(8,"section21","");
            Node c211 = new LeafNode(6,"c211");
            Node c212 = new LeafNode(7,"c212");
            root.add(chapter1);
            root.add(chapter2);
            root.add(r1);
            chapter1.add(c11);
            chapter1.add(c12);
            chapter2.add(b21);
            b21.add(c211);
            b21.add(c212);
            //显示树状结构
            displayTree(root, 0);
        }
    
        /**
         * 递归显示树状结构
         * @param node
         * @param depth
         */
        static void displayTree(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) {
                    displayTree(n, depth + 1);
                }
            }
        }
    }

    看到这里是不是觉得非常熟悉,工作中想必大家都用过吧。

  • 相关阅读:
    张小龙:微信十周年总结
    天呐!!!竟还有人不知道如何将Python程序打包成exe
    Making Games with Python & Pygame 中文翻译
    turtle怎么引入背景图片
    Python少儿编程全集(一):一只小海龟(turtle库的使用)
    C/C++基础编程
    少儿编程论坛,汇集所有少儿编程资源!!!
    少儿编程:认识python中的turtle库(一)
    博客导航栏,衣渐衫衣终不悔,沉淀技术这十年(持续更新...)
    SpringBoot学习笔记【尚硅谷】
  • 原文地址:https://www.cnblogs.com/sx-bj-srr/p/composite.html
Copyright © 2020-2023  润新知