首页 > 其他 > 详细

设计模式之composit

时间:2015-04-22 15:12:29      阅读:263      评论:0      收藏:0      [点我收藏+]
对象以树形结构组织起来,以达成“部分-整体”的层次结构 

class Program

    {
        static void Main(string[] args)
        {
            CompositionEquipment equip = new CompositionEquipment();
            equip[0] = new Guest(1,"1");
            equip[-1] = new Guest(2, "2");
            equip[2] = new Guest(3, "3");
            equip[2] = new Guest(4, "4");
            IEnumerator ietor = equip.GetEnumerator();
            while (ietor.MoveNext())
            {
                Console.WriteLine(((Guest)(ietor.Current)).id);
                Console.WriteLine(((Guest)(ietor.Current)).name);
            }
            foreach (Guest gu in equip)
            {
                Console.WriteLine(gu.id);
                Console.WriteLine(gu.name);
            }
            Console.ReadKey();
        }
    }
    public struct Guest {
        public int id;
        public string name;
        public Guest(int id, string name) 
        {
            this.id = id;
            this.name = name;
        }
    }
    public class CompositionEquipment : IEnumerator 
    {
        private List<object> equip = new List<object>();
        public object this[int index]{
            get{return equip[index];}
            set{equip.Add(value);}
        }
        public int Count(){
            return equip.Count;
        }
        public IEnumerator GetEnumerator()
        {
            return new CompositionIterator(this);
        }
        public object Current
        {
            get { throw new NotImplementedException(); }
        }
        public bool MoveNext()
        {
            throw new NotImplementedException();
        }
        public void Reset()
        {
            throw new NotImplementedException();
        }
    }
    public class CompositionIterator:IEnumerator
    {
        private CompositionEquipment equip;
        private int currentindex;
        public CompositionIterator(CompositionEquipment equip)
        {
            this.equip = equip;
            this.currentindex = -1;
        }
        object IEnumerator.Current
        {
            get {return equip[currentindex]; }
        }
        public bool MoveNext()
        {
            currentindex++;
            return equip.Count() > currentindex;
        }
        public void Reset()
        {
            currentindex = -1;
        }
    }

设计模式之composit

原文:http://www.cnblogs.com/sky7728/p/4447508.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!