设计模式-结构型模式-组合模式

组合模式(Composite Pattern):组合多个对象形成树形结构以表示具有"部分---整体"关系的层次结构。组合模式对单个对象(即叶子对象)和组合对象(即容器对象)的使用具有一致性,又可以称为"部分---整体"(Part-Whole)模式,它是一种对象结构型模式。

"当你发现需求中是体现部分与整体层次的结构时,以及你希望用户可以忽略组合对象与单个对象的不同,统一地使用组合结构中的所有对象时,就应该考虑用组合模式了。"

复制代码
首先,我们定义一个Component接口,这是所有组件的基类:

// 组件接口
public interface Component {
    void display(int depth);
}

接下来,我们定义Leaf类,表示员工(叶子节点):
// 员工类(叶子节点)
public class Leaf implements Component {
    private String name;

    public Leaf(String name) {
        this.name = name;
    }

    @Override
    public void display(int depth) {
        // 打印缩进和叶子节点信息
        for (int i = 0; i < depth; i++) {
            System.out.print("--");
        }
        System.out.println("Leaf: " + name);
    }
}

然后,我们定义Composite类,表示部门(复合节点):
import java.util.ArrayList;
import java.util.List;

// 部门类(复合节点)
public class Composite implements Component {
    private String name;
    private List<Component> children = new ArrayList<>();

    public Composite(String name) {
        this.name = name;
    }

    // 添加子组件
    public void add(Component component) {
        children.add(component);
    }

    // 移除子组件
    public void remove(Component component) {
        children.remove(component);
    }

    @Override
    public void display(int depth) {
        // 打印缩进和复合节点信息
        for (int i = 0; i < depth; i++) {
            System.out.print("--");
        }
        System.out.println("Composite: " + name);

        // 递归显示子组件
        for (Component child : children) {
            child.display(depth + 1);
        }
    }
}

最后,我们编写一个Client类来测试我们的组合模式:
public class Client {
    public static void main(String[] args) {
        // 创建组织结构
        Composite root = new Composite("公司");

        // 创建部门
        Composite departmentIT = new Composite("IT部");
        Composite departmentHR = new Composite("HR部");

        // 创建员工
        Leaf employeeAlice = new Leaf("Alice");
        Leaf employeeBob = new Leaf("Bob");

        // 将员工加入部门
        departmentIT.add(employeeAlice);
        departmentIT.add(employeeBob);

        // 将部门加入公司
        root.add(departmentIT);
        root.add(departmentHR);

        // 显示整个组织结构
        root.display(0);
    }
}
当运行Client类的main方法时,会输出以下结构:
Composite: 公司
--Composite: IT部
----Leaf: Alice
----Leaf: Bob
--Composite: HR部
相关推荐
Query*19 分钟前
Java 设计模式——工厂模式:从原理到实战的系统指南
java·python·设计模式
庸了个白2 小时前
一种面向 AIoT 定制化场景的服务架构设计方案
mqtt·设计模式·系统架构·aiot·物联网平台·动态配置·解耦设计
Meteors.6 小时前
23种设计模式——访问者模式 (Visitor Pattern)
设计模式·访问者模式
Vallelonga7 小时前
Rust 设计模式 Marker Trait + Blanket Implementation
开发语言·设计模式·rust
en-route7 小时前
设计模式的底层原理——解耦
设计模式
杯莫停丶7 小时前
设计模式之:工厂方法模式
设计模式·工厂方法模式
Deschen7 小时前
设计模式-抽象工厂模式
java·设计模式·抽象工厂模式
粘豆煮包8 小时前
系统设计 System Design -4-2-系统设计问题-设计类似 TinyURL 的 URL 缩短服务 (改进版)
设计模式·架构
top_designer10 小时前
告别“静态”VI手册:InDesign与AE打造可交互的动态品牌规范
设计模式·pdf·交互·vi·工作流·after effects·indesign
非凡的世界11 小时前
深入理解 PHP 框架里的设计模式
开发语言·设计模式·php