【設計模式】之組合模式

  • UML

  • 原型

//組件抽象類
    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 Composite : Component
    {
        private List<Component> children = new List<Component>();
        public Composite(string name) : base(name)
        {
        }

        public override void Add(Component c)
        {
            children.Add(c);
        }

        public override void Display(int depth)
        {
            Console.WriteLine(new String('-', depth) + name);
            foreach(Component component in children)
            {
                component.Display(depth + 1);
            }
        }

        public override void Remove(Component c)
        {
            children.Remove(c);
        }
    }
//葉節點
    class Leaf : Component
    {
        public Leaf(String name):base(name)
        {

        }
        public override void Add(Component c)
        {
            Console.WriteLine("Cannot add to a leaf");
        }

        public override void Display(int depth)
        {
            Console.WriteLine(new String('-', depth) + name);
        }

        public override void Remove(Component c)
        {
            Console.WriteLine("Cannot remove from a leaf");
        }
    }
class Program
    {
        static void Main(string[] args)
        {
            Composite root = new Composite("Root");
            Composite A = new Composite("A");
            Composite B = new Composite("B");
            Leaf C = new Leaf("C");
            Leaf D = new Leaf("D");
            Leaf E = new Leaf("E");
            Leaf F = new Leaf("F");
            root.Add(A);
            root.Add(B);
            A.Add(C);
            A.Add(D);
            B.Add(E);
            B.Add(F);
            root.Display(0);
            Console.WriteLine();
            B.Remove(F);
            root.Display(0);
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章