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

时间:2024-01-26 22:14:49

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

代码如下:

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);
            }
        }
    }
}

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