1. 介绍
组合模式,是一种数据结构和算法的抽象,其中,数据可以表示成树形结构的特点,递归的处理 每个子树,依次简化代码实现。使用组合模式的前提在于,你的业务场景必须能够表示成树形结构,所以,在应用开发中:组合模式的应用场景也比较局限,它并不是一种很常见的设计模式
2. 主流游戏架构(ECS)和组合模式
ECS(实体-组件-系统) 是组合模式的一种高级进化,它把系统逻辑也“分离”出来,形成:
✅ 特点
高性能(适合大规模对象)
数据驱动(紧密内存布局)
解耦彻底,便于并行处理
组合比继承更灵活
🧠 组合模式 vs ECS 架构:关系与对比
🎮 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} 死后掉落战利品。");
}
}