组合模式(Composite)

有时候又叫做部分-整体模式,它使我们树型结构的问题中,模糊了简单元素和复杂元素的概念,客户程序可以像处理简单元素一样来处理复杂元素,从而使得客户程序与复杂元素的内部结构解耦
组合模式让你可以优化处理递归或分级数据结构。有许多关于分级数据结构的例子,使得组合模式非常有用武之地。关于分级数据结构的一个普遍性的例子是你每次使用电脑时所遇到的:文件系统。文件系统由目录和文件组成。每个目录都可以装内容。目录的内容可以是文件,也可以是目录。按照这种方式,计算机的文件系统就是以递归结构来组织的。如果你想要描述这样的数据结构,那么你可以使用组合模式Composite。
将对象组合成树形结构以表示“部分整体”的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。
 
------A总公司
--------A1分公司
--------A2分公司
using System;
using System.Collections.Generic;

namespace DoFactory.GangOfFour.Composite.Structural
{
    class MainApp
    {
       
        static void Main()
        {
            // Create a tree structure
            Composite root = new Composite("总公司A");
            root.Add(new Leaf("分公司A1"));
            root.Add(new Leaf("分公司A2"));
            root.LineOfDuty();
            Console.ReadKey();
        }
    }

 
    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 LineOfDuty();
    }

    class Composite : Component
    {
        private List<Component> _children = new List<Component>();

        public Composite(string name)
            : base(name)
        {
        }

        public override void Add(Component component)
        {
            _children.Add(component);
        }

        public override void Remove(Component component)
        {
            _children.Remove(component);
        }

        public override void LineOfDuty()
        {
            Console.WriteLine("地沟油批发: " + name);

            // Recursively display child nodes
            foreach (Component component in _children)
            {
                component.LineOfDuty();
            }
        }
    }

    class Leaf : Component
    {
        // Constructor
        public Leaf(string name)
            : base(name)
        {
        }

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

        public override void Remove(Component c)
        {
            Console.WriteLine("Cannot remove from a leaf");
        }

        public override void LineOfDuty()
        {
            Console.WriteLine("地沟油批发: "+name);
        }
    }
}

 

 
posted @ 2014-07-10 14:00  欢呼雀跃  阅读(160)  评论(0)    收藏  举报