首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >设计模式--组合模式

设计模式--组合模式

原创
作者头像
软件架构师Michael
发布2023-07-06 09:31:25
发布2023-07-06 09:31:25
31400
代码可运行
举报
运行总次数:0
代码可运行

组合模式是一种结构型设计模式,它允许你将对象组合成树状结构来表示整体-部分的层次关系。组合模式使得客户端对单个对象和组合对象的使用具有一致性。在组合模式中,单个对象称为叶节点,而组合对象称为容器节点。

使用组合模式可以构建具有层次结构的对象,这些对象可以以相同的方式进行操作。这种模式有助于简化处理复杂对象结构的算法。

下面是一个使用C#编写的组合模式的代码示例:

代码语言:javascript
代码运行次数:0
运行
复制
using System;
using System.Collections.Generic;

// 组件类,可以是叶节点或容器节点的基类
abstract class Component
{
    protected string name;

    public Component(string name)
    {
        this.name = name;
    }

    public abstract void Add(Component component);
    public abstract void Remove(Component component);
    public abstract void Display(int depth);
}

// 叶节点类,表示组合中的叶节点对象
class Leaf : Component
{
    public Leaf(string name) : base(name) { }

    public override void Add(Component component)
    {
        Console.WriteLine("Cannot add to a leaf");
    }

    public override void Remove(Component component)
    {
        Console.WriteLine("Cannot remove from a leaf");
    }

    public override void Display(int depth)
    {
        Console.WriteLine(new string('-', depth) + name);
    }
}

// 容器节点类,表示组合中的容器节点对象
class Composite : Component
{
    private List<Component> children = new List<Component>();

    public Composite(string name) : base(name) { }

    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) + name);

        foreach (Component component in children)
        {
            component.Display(depth + 2);
        }
    }
}

// 客户端代码
class Client
{
    static void Main(string[] args)
    {
        // 创建树状结构
        Composite root = new Composite("Root");
        root.Add(new Leaf("Leaf A"));
        root.Add(new Leaf("Leaf B"));

        Composite composite = new Composite("Composite X");
        composite.Add(new Leaf("Leaf XA"));
        composite.Add(new Leaf("Leaf XB"));

        root.Add(composite);

        Leaf leaf = new Leaf("Leaf C");
        root.Add(leaf);
        root.Remove(leaf);

        // 调用组合对象的方法,执行操作
        root.Display(1);

        Console.ReadLine();
    }
}

运行结果:

组合模式
组合模式

在上述代码中,`Component`是组件类,它包含了添加、移除和展示组件的方法。`Leaf`是叶节点类,表示组合中的叶节点对象,而`Composite`是容器节点类,表示组合中的容器节点对象。

在客户端代码中,我们创建了一个树状结构,并对组合对象进行了操作,最后展示整个树形结构。

【小结】

日拱一卒,持续进化,持续迭代。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档