设计模式——组合模式

组合模式(Composite Pattern)是一种结构型设计模式,它的主要目标是将对象组织到树形结构中,并且能够以统一的方式处理单个对象和组合对象。这种模式使得客户端可以一致地对待单个对象以及对象的集合。

原理

  • 抽象组件(Component): 定义所有组件共有的接口,包括叶子节点(Leaf)和容器节点(Composite)都继承自这个接口。
  • 叶子组件(Leaf): 是组合中的基本元素,它没有子组件,实现了抽象组件定义的操作。
  • 容器组件(Composite): 包含多个子组件,每个子组件都是一个抽象组件的实例;容器组件提供管理其子组件的方法,并实现与抽象组件相同的接口,以便客户端能一致地访问叶节点和容器节点。

Java代码示例

java 复制代码
// 抽象组件
public abstract class Component {
    public abstract void add(Component component);
    public abstract void remove(Component component);
    public abstract void operation();
}

// 叶子组件(例如:文本文件)
public class Leaf extends Component {
    @Override
    public void add(Component component) {
        throw new UnsupportedOperationException("Leaf doesn't support adding components");
    }

    @Override
    public void remove(Component component) {
        throw new UnsupportedOperationException("Leaf doesn't support removing components");
    }

    @Override
    public void operation() {
        System.out.println("Executing operation on a leaf component.");
    }
}

// 容器组件(例如:目录)
public class Composite extends Component {
    private List<Component> children = new ArrayList<>();

    @Override
    public void add(Component component) {
        children.add(component);
    }

    @Override
    public void remove(Component component) {
        children.remove(component);
    }

    @Override
    public void operation() {
        for (Component child : children) {
            child.operation();
        }
        System.out.println("Executing operation on a composite component and its children.");
    }
}

// 使用示例
public class Client {
    public static void main(String[] args) {
        // 创建叶子节点
        Component leaf1 = new Leaf();
        Component leaf2 = new Leaf();

        // 创建容器节点并添加叶子节点
        Composite composite = new Composite();
        composite.add(leaf1);
        composite.add(leaf2);

        // 对单个叶子和组合执行操作
        leaf1.operation();
        composite.operation();
    }
}

想象一下你正在管理一家公司,这家公司由员工组成,有些员工直接向你报告(叶子节点),有些员工是团队领导,他们手下还有其他员工(容器节点)。组合模式允许你对每位员工或整个团队下达命令时使用相同的方式,无论是单独与某位员工交谈,还是召开团队会议进行沟通。

应用场景

  • 文件系统中的目录和文件结构:目录可以包含文件和其他目录,而文件则没有子项。
  • 组合图形对象,如图形编辑器中的图形及其组合(组)。
  • HTML文档结构,其中元素可以嵌套其他元素形成层级结构。

适用性

  • 需要表示部分-整体层次结构的问题域。
  • 客户端需要一致地处理单个对象和对象集合的情况。
  • 想要简化在复杂对象树中进行操作的代码时。
相关推荐
Yu_Lijing2 小时前
基于C++的《Head First设计模式》笔记——状态模式
c++·笔记·设计模式
Engineer邓祥浩3 小时前
设计模式学习(18) 23-16 迭代器模式
学习·设计模式·迭代器模式
老蒋每日coding5 小时前
AI Agent 设计模式系列(十三)—— 人机协同模式
人工智能·设计模式·langchain
老蒋每日coding6 小时前
AI Agent 设计模式系列(十二)—— 异常处理和恢复模式
人工智能·设计模式
小码过河.7 小时前
设计模式——抽象工厂模式
设计模式·抽象工厂模式
国强_dev20 小时前
量体裁衣在技术方案中的应用
设计模式·系统架构
Engineer邓祥浩1 天前
设计模式学习(16) 23-14 命令模式
学习·设计模式·命令模式
Maddie_Mo1 天前
智能体设计模式 第二章:路由模式
设计模式
一条闲鱼_mytube1 天前
智能体设计模式(五)人机协同-知识检索RAG-智能体间通信
网络·人工智能·设计模式
小码过河.1 天前
设计模式——建造者模式
单片机·设计模式·建造者模式