学习之路---java设计模式-组合模式Composite

树状结构专用模式

学习之路---java设计模式-组合模式Composite_第1张图片

package org.example.ms.composite;

/**
 * @author Gavin.luo
 * @title: Node
 * @projectName MyData
 * @description:
 * @date 2022/3/16 9:17
 */
public abstract class Node {
    abstract void p();
}
package org.example.ms.composite;

/**
 * @author Gavin.luo
 * @title: LeafNode
 * @projectName MyData
 * @description:
 * @date 2022/3/16 9:18
 */
public class LeafNode extends Node {
    String content;

    public LeafNode(String content) {
        this.content = content;
    }

    @Override
    void p() {
        System.out.println(content);
    }
}

package org.example.ms.composite;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Gavin.luo
 * @title: BranchNode
 * @projectName MyData
 * @description:
 * @date 2022/3/16 9:20
 */
public class BranchNode extends Node{
    List nodes = new ArrayList<>();
    String name;
    public BranchNode(String name){
        this.name = name;
    }

    @Override
    void p() {
        System.out.println(name);
    }

    public void add(Node node){
        nodes.add(node);
    }
}
package org.example.ms.composite;

/**
 * @author Gavin.luo
 * @title: Test
 * @projectName MyData
 * @description: 测试组合模式
 * @date 2022/3/16 9:16
 */
public class Test {
    public static void main(String[] args) {
        BranchNode root = new BranchNode("root");
        BranchNode branchNode1 = new BranchNode("11111111");
        BranchNode branchNode2 = new BranchNode("22222222");
        Node n1=new LeafNode("n1");
        Node n2=new LeafNode("n2");
        root.add(branchNode1);
        root.add(branchNode2);
        branchNode1.add(n1);
        branchNode1.add(n2);

        BranchNode branchNode22 = new BranchNode("22222222-2");
        Node n21=new LeafNode("n21");
        Node n22=new LeafNode("n22");
        branchNode22.add(n21);
        branchNode22.add(n22);
        root.add(branchNode22);
        tree(root,0);
    }

    static void tree(Node node,int depth){
        for(int i = 0 ; i

学习之路---java设计模式-组合模式Composite_第2张图片

 

你可能感兴趣的:(Java,学习,设计模式,组合模式)