组合模式 c# 组合模式

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

组合模式 c# 组合模式

  2021-03-19 我要评论
想了解c# 组合模式的相关内容吗,在本文为您仔细讲解组合模式的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:组合模式,下面大家一起来学习吧。
结构图:

抽象对象:
复制代码 代码如下:

    abstract class Component
    {
        protected string name;
        public Component(string name)
        {
            this.name = name;
        }
        public abstract void Add(Component c);
        public abstract void Remove(Component c);
        public abstract void Display(int depth);
    }

无子节点的:
复制代码 代码如下:

    class Leaf : Component
    {
        public Leaf(string name)
            : base(name)
        { }
        public override void Add(Component c)
        {
            //throw new NotImplementedException();
            Console.WriteLine("Cannot add to a Leaf");
        }
        public override void Remove(Component c)
        {
            //throw new NotImplementedException();
            Console.WriteLine("Cannot remove to a Leaf");
        }
        public override void Display(int depth)
        {
            //throw new NotImplementedException();
            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 c)
        {
            //throw new NotImplementedException();
            children.Add(c);
        }
        public override void Remove(Component c)
        {
            //throw new NotImplementedException();
            children.Remove(c);
        }
        public override void Display(int depth)
        {
            //throw new NotImplementedException();
            Console.WriteLine(new string('-', depth) + name);
            foreach (Component component in children)
            {
                component.Display(depth + 2);
            }
        }
    }

 主函数调用:
复制代码 代码如下:

    class Program
    {
        static void Main(string[] args)
        {
            Composite root = new Composite("root");
            root.Add(new Leaf("Leaf A"));
            root.Add(new Leaf("Leaf B"));
            Composite comp = new Composite("Composite X");
            comp.Add(new Leaf("Leaf XA"));
            comp.Add(new Leaf("Leaf XB"));
            root.Add(comp);
            Composite comp2 = new Composite("Composite X");
            comp2.Add(new Leaf("Leaf XYA"));
            comp2.Add(new Leaf("Leaf XYB"));
            comp.Add(comp2);
            root.Display(1);
            Console.ReadKey();
        }
    }
 

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们