.NET 设计模式—组合模式(Composite Pattern)

发布于:2024-04-11 ⋅ 阅读:(190) ⋅ 点赞:(0)

简介

组合模式是一种结构型设计模式,它允许将对象组合成树形结构以表示“整体/部分”层次结构。该模式可以让客户端通过统一的方式处理单个对象和对象组合,从而使得代码更加简洁、灵活。

角色

  • Component(组件):定义了对象接口,可以包括一些默认行为和子节点管理方法。
  • Leaf(叶子节点):实现了 Component 接口,表示树形结构中的叶子节点对象。
  • Composite(组合节点):实现了 Component 接口,表示树形结构中的非叶子节点对象,可以管理子节点,并实现了与子节点有关的操作。

优点

  • 统一的接口:客户端可以通过统一的方式来处理单个对象和对象组合。
  • 简化客户端代码:客户端不需要知道对象组合的具体实现方式,从而使得客户端代码更加简洁、灵活。
  • 可扩展性:可以通过添加新的组合节点和叶子节点来扩展对象的层次结构。

缺点

  • 限制类型:组合模式要求所有组合对象都实现相同的接口,这可能会限制对象类型的灵活性。
  • 不容易限制组件类型:在某些情况下,我们可能希望限制某个组合对象只能包含特定类型的子节点,但组合模式并不容易实现这种限制

应用场景

  • 需要构建对象层次结构的场景。
  • 需要统一处理单个对象和对象组合的场景。
  • 需要动态地添加或删除对象的场景。

实现

using System.Collections.Generic;
 
// 组合模式的抽象组件
abstract class Component
{
    public abstract void Add(Component component);
    public abstract void Remove(Component component);
    public abstract void Display(int depth);
}
 
// 叶子节点,没有子节点的节点
class Leaf : Component
{
    public override void Add(Component component)
    {
        // 叶子节点不能添加子节点,抛出异常
        throw new System.NotImplementedException();
    }
 
    public override void Remove(Component component)
    {
        // 叶子节点没有子节点,抛出异常
        throw new System.NotImplementedException();
    }
 
    public override void Display(int depth)
    {
        // 显示叶子节点的信息
        Console.WriteLine(new String('-', depth) + " Leaf");
    }
}
 
// 容器节点,可以包含子节点
class Composite : Component
{
    private readonly List<Component> _children = new List<Component>();
 
    public override void Add(Component component)
    {
        _children.Add(component);
    }
 
    public override void Remove(Component component)
    {
        _children.Remove(component);
    }
 
    public override void Display(int depth)
    {
        Console.WriteLine(new String('-', depth) + " Composite");
 
        // 显示所有子节点
        foreach (var child in _children)
        {
            child.Display(depth + 2);
        }
    }
}


网站公告

今日签到

点亮在社区的每一天
去签到