zoukankan      html  css  js  c++  java
  • 组合模式

    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);
                }
            }
        }
    }
  • 相关阅读:
    2019 SDN上机第7次作业
    第01组 Beta冲刺(4/5)
    第01组 Beta冲刺(3/5)
    第01组 Beta冲刺(2/5)
    第01组 Beta冲刺(1/5)
    2019 SDN上机第6次作业
    2019 SDN上机第5次作业
    SDN课程阅读作业(2)
    第01组 Alpha事后诸葛亮
    第01组 Alpha冲刺(6/6)
  • 原文地址:https://www.cnblogs.com/YC-L/p/14257559.html
Copyright © 2011-2022 走看看