1. 介绍

组合模式,是一种数据结构和算法的抽象,其中,数据可以表示成树形结构的特点,递归的处理 每个子树,依次简化代码实现。使用组合模式的前提在于,你的业务场景必须能够表示成树形结构,所以,在应用开发中:组合模式的应用场景也比较局限,它并不是一种很常见的设计模式

2. 主流游戏架构(ECS)和组合模式

ECS(实体-组件-系统) 是组合模式的一种高级进化,它把系统逻辑也“分离”出来,形成:

部件

说明

Entity

游戏对象,只是个 ID(如 Player、Monster)

Component

只存数据,不含逻辑(如 Position、Health、Velocity)

System

操作组件数据的逻辑(如 MovementSystem、DamageSystem)

✅ 特点

  • 高性能(适合大规模对象)

  • 数据驱动(紧密内存布局)

  • 解耦彻底,便于并行处理

  • 组合比继承更灵活

🧠 组合模式 vs ECS 架构:关系与对比

对比维度

组合模式

ECS 架构

目标

提高灵活性

提高灵活性 + 性能

组件职责

数据 + 行为

只负责数据

行为实现

组件自己处理

System 统一处理

解耦程度

较高

非常高(系统也被解耦)

性能关注

一般

非常关注,结构化数据,易于并行

🎮 ECS 是组合模式的“演化升级”

  • ECS 完全基于组合模式的核心思想:对象的行为由组件组合定义

  • ECS 进一步把逻辑抽离出来做成 System,实现 数据和行为的完全解耦

  • Unity 的 DOTS ECS 就是一个代表性实现,目标是高性能数据驱动。

3. 代码示例

 public class CompositeDesign
    {
        // static void Main()
        // {

        //     Entity entity = new Entity("哥布林");


        //     entity.AddComponent(new MoveComponent());
        //     entity.AddComponent(new AttackComponent());
        //     entity.AddComponent(new DropComponent());

        //     entity.Update();
        // }
    }
    /// <summary>
    /// 组件接口
    /// </summary>
    public interface IComponent
    {
        public void Update(Entity entity);
    }
    // 抽象实体
    public class Entity
    {
        public string Name { get; }

        private List<IComponent> compsites = new List<IComponent>();

        public Entity(string name)
        {
            this.Name = name;
        }

        public void AddComponent(IComponent component)
        {
            compsites.Add(component);
        }

        public void Update()
        {
            foreach (var component in compsites)
            {
                component.Update(this);
            }
        }
    }

    // 具体实体
    public class MoveComponent : IComponent
    {
        public void Update(Entity entity)
        {
            Console.WriteLine($"{entity.Name} 正在移动...");
        }
    }

    public class AttackComponent : IComponent
    {
        public void Update(Entity entity)
        {
            Console.WriteLine($"{entity.Name} 发起攻击!");
        }
    }

    public class DropComponent : IComponent
    {
        public void Update(Entity entity)
        {
            Console.WriteLine($"{entity.Name} 死后掉落战利品。");
        }
    }