首页 > 其他 > 详细

设计模式 之 迭代器模式

时间:2014-03-22 07:26:26      阅读:379      评论:0      收藏:0      [点我收藏+]

迭代器提供了一种方法顺序访问一个聚合对象,而不暴露对象的内部细节  。net中的foreach就是典型的迭代器模式

图示:

bubuko.com,布布扣

代码:

  车上售票员对乘客售票

  class Program
    {
        static void Main(string[] args)
        {
            ConcreteAggregate a = new ConcreteAggregate();
            a[0] = "大鸟";
            a[1] = "xiao菜";
            a[2] = "行李";
            a[3] = "老外";
            a[4] = "内部员工";
            a[5] = "小偷";

            Iterator i = new ConcreteIterator(a);
            object item = i.First();
            while (!i.IsDone()) {
                Console.WriteLine("{0}请买车票!",i.CurrentItem());
                i.Next();
            }
            Console.Read();



        }
    }
    //抽象迭代器类
    abstract class Iterator {
        public abstract object First();
        public abstract object Next();
        public abstract bool IsDone();
        public abstract object CurrentItem();
    }
    //聚合抽象类
    abstract class Aggregate {
        public abstract Iterator createIterator(); //创建迭代器
    }
    //具体迭代器类
    class ConcreteIterator : Iterator {
        private ConcreteAggregate aggregate;
        private int current = 0;
        public ConcreteIterator(ConcreteAggregate aggregate) {
            this.aggregate = aggregate;
        }

        public override object First()
        {
            //throw new NotImplementedException();
            return aggregate[0];
        }
        public override object Next()
        {
            //throw new NotImplementedException();
            object ret = null;
            current++;
            if (current < aggregate.Count) {
                ret = aggregate[current];
            }
            return ret;
        }
        public override bool IsDone()
        {
            //throw new NotImplementedException();
            return current >= aggregate.Count ? true : false;
        }
        public override object CurrentItem()
        {
            //throw new NotImplementedException();
            return aggregate[current];
        }
       
    }
    class ConcreteAggregate : Aggregate { 
        //声明一个IList 泛型变量 用来存放聚合对象
        private IList<object> items=new List<object>();
        public override Iterator createIterator()
        {
            //throw new NotImplementedException();
            return new ConcreteIterator(this);

        }
        public int Count {
            get { return items.Count; }
        }
        public object this[int index] {
            get { return items[index]; }
            set { items.Insert(index,value); }
        }
    }

运行结果:

bubuko.com,布布扣

设计模式 之 迭代器模式,布布扣,bubuko.com

设计模式 之 迭代器模式

原文:http://blog.csdn.net/buyingfei8888/article/details/21699663

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