【设计模式-07】Composite组合模式

简要说明

一、代码实现

  • 定义抽象节点类 Node**,定义抽象方法** public abstract void print();
  • 定义叶子节点类 LeafNode**,继承Node节点,实现** **print()**抽象方法,叶子节点没有子节点
  • 定义子节点类 BranchNode**,继承Node节点,实现** **print()**抽象方法,子节点既可以有子节点,也又可以有叶子节点
  • 定义一个树状目录结构,使用递归打印树状目录结构
复制代码
import java.util.ArrayList;
import java.util.List;

/**
* @description: composite组合模式
* @author: flygo
* @time: 2022/7/20 14:05
*/
public class CompositeMain {
    
    public static void main(String[] args) {
        BranchNode root = new BranchNode("root");
        
        BranchNode chapter1 = new BranchNode("chapter1");
        BranchNode chapter2 = new BranchNode("chapter2");
        
        Node r1 = new LeafNode("r1");
        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).add(chapter2).add(r1);
        chapter1.add(c11).add(c12);
        chapter2.add(b21);
        b21.add(c211).add(c212);
        
        tree(root, 0);
    }
    
    private static void tree(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) {
                tree(n, depth + 1);
            }
        }
    }
}

abstract class Node {
    public abstract void print();
}

/**
* @description: 叶子节点-不能有子节点
* @author: flygo
* @time: 2022/7/20 14:10
*/
class LeafNode extends Node {
    String content;
    
    public LeafNode(String content) {
        this.content = content;
    }
    
    @Override
    public void print() {
        System.out.println(content);
    }
}

/**
* @description: 子节点-可以有子节点和叶子节点
* @author: flygo
* @time: 2022/7/20 14:10
*/
class BranchNode extends Node {
    
    // 子节点可以有子节点和叶子节点
    List<Node> nodes = new ArrayList<>();
    
    String name;
    
    public BranchNode(String name) {
        this.name = name;
    }
    
    @Override
    public void print() {
        System.out.println(name);
    }
    
    public BranchNode add(Node node) {
        this.nodes.add(node);
        return this;
    }
}

二、源码地址

https://github.com/jxaufang168/Design-Patternshttps://github.com/jxaufang168/Design-Patterns

相关推荐
火车叨位去19496 分钟前
软件设计模式(tyutJAVA 状态模式实验)
设计模式·状态模式
喝茶与编码9 小时前
工厂模式+抽象类 实战指南(基于文档导出业务)
设计模式
昨天的猫13 小时前
原来项目中的观察者模式是这样玩的
后端·设计模式
2301_7951672014 小时前
玩转Rust高级应用 如何进行面向对象设计模式的实现,实现状态模式
设计模式·rust·状态模式
星夜泊客1 天前
Unity 游戏开发中的防御性编程与空值处理实践
unity·设计模式·游戏引擎
Adellle1 天前
设计模式的介绍
设计模式
达斯维达的大眼睛1 天前
设计模式-单列模式
设计模式·cpp
Javatutouhouduan1 天前
记一次redis主从切换导致的数据丢失与陷入只读状态故障
java·redis·设计模式·java面试·高可用·java后端·java程序员
数据知道1 天前
Go语言设计模式:抽象工厂模式详解
设计模式·golang·抽象工厂模式·go语言
数据知道1 天前
Go语言设计模式:组合模式详解
设计模式·golang·组合模式·go语言