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

发布了18 篇原创文章 · 获赞 17 · 访问量 2692

猜你喜欢

转载自blog.csdn.net/chasinghope/article/details/104220699