国产探花免费观看_亚洲丰满少妇自慰呻吟_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();
        }
    }
 
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 邻水| 阳信县| 子长县| 滁州市| 云和县| 东乡县| 永济市| 弥勒县| 新泰市| 苏尼特右旗| 庄河市| 汉源县| 蒲江县| 沅江市| 南部县| 页游| 武宁县| 塔河县| 娄烦县| 馆陶县| 泾阳县| 平邑县| 克拉玛依市| 泰兴市| 蓬溪县| 个旧市| 武威市| 七台河市| 湛江市| 泽普县| 新田县| 东海县| 上虞市| 景宁| 武邑县| 图木舒克市| 龙州县| 晋中市| 辽宁省| 丰都县| 韶山市|