国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C# > 正文

c# 組合模式

2020-01-24 03:40:31
字體:
來源:轉載
供稿:網友
結構圖:

抽象對象:
復制代碼 代碼如下:

    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();
        }
    }
 
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 北流市| 凌云县| 兴海县| 五华县| 龙胜| 育儿| 特克斯县| 信宜市| 泗阳县| 上杭县| 来宾市| 钟山县| 广饶县| 元氏县| 西和县| 桃源县| 邹城市| 准格尔旗| 秦安县| 增城市| 房产| 涡阳县| 广南县| 毕节市| 三穗县| 海伦市| 平顺县| 崇文区| 富蕴县| 晋宁县| 郓城县| 佛山市| 沈阳市| 阿合奇县| 泌阳县| 涪陵区| 武汉市| 松潘县| 南丰县| 梁河县| 左云县|