C# 设计模式———组合模式

本文深入探讨了组合模式的设计理念,展示了如何通过将对象组织成树形结构来表达部分与整体的关系,使用户能够一致地操作单个对象和组合对象。通过C#示例代码,详细解释了组合模式的实现方式及其在树形菜单、文件管理和编程语言分类等场景的应用。

组合模式

将对象组合成树形结构以表示“部分——整体”的层次结构,使得用户对单个对象使用具有一致性。
在这里插入图片描述
UML补充说明:树枝和叶子实现统一接口,树枝内部组合该接口,树枝内部组合该接口,并且含有内部属性 List,里面放 Component。
优缺点:

优点缺点
高层模块调用简单。在使用组合模式时,其叶子和树枝的声明都是实现类,而不是接口,违反了依赖倒置原则。
节点增加自由/
总结:将相同类型的东西组合在一起形成一种特有的功能。

C# 组合模式Demo

在这里插入图片描述

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CompositePattern
{
    class Program
    {
        static void Main(string[] args)
        {
            Composite root = new Composite() { Name = "root" };
            Composite net_tech = new Composite() { Name = "net技术" };


            net_tech.Add(new Leaf() { Name = "net新手" });
            net_tech.Add(new Leaf() { Name = "C#" });
            root.Add(net_tech);

            Composite language = new Composite() { Name = "编程语言" };
            language.Add(new Leaf() { Name = "Java" });
            root.Add(language);

            root.Display(1);
        }
    }

    public abstract class Component
    {
        protected List<Component> children = new List<Component>();
        public string Name { get; set; }

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

    public class Leaf : Component
    {       
        public override void Add(Component component)
        {
  
        }
        public override void Remove(Component component)
        {

        }

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


    public class Composite : Component
    {
        public override void Add(Component component)
        {
            this.children.Add(component);
        }

        public override void Display(int depth)
        {
            Console.WriteLine(new string('-', depth)+"     "+this.Name    );
            /// 深度遍历
            foreach (var item in children)
            {
                item.Display(depth + 2);
            }
        }

        public override void Remove(Component component)
        {
            this.children.Remove(component);
        }
    }
}

测试结果:
在这里插入图片描述
Hints:
使用场景:部分、整体场景,如树形菜单,文件、文件夹的管理。

参考资料

https://www.runoob.com/design-pattern/composite-pattern.html
更多:

23种设计模式C#

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值