设计模式-》迭代器模式

例子

    public interface ITerator<TSource>
    {
        TSource Current { get; }
        bool HasNext();
        void MoveNext();
    }

    public class ArrayIterator<TSource> : ITerator<TSource>
    {
        private TSource[] Sources;

        public ArrayIterator(TSource[] sources)
        {
            this.Sources = sources;
            this.index = 0;
        }

        private uint index;
        private TSource source;

        public TSource Current
        {
            get { return source; }
        }

        public bool HasNext()
        {
            return this.index < this.Sources.Length;
        }

        public void MoveNext()
        {
            this.source = this.Sources[index];
            this.index++;
        }
    }


    public interface IAggregate<TSource>
    {
        ITerator<TSource> GetIterator();
    }


    public class ArrayAggregate<TSource> : IAggregate<TSource>
    {
        private TSource[] Sources;

        public ArrayAggregate(TSource[] sources)
        {
            this.Sources = sources;
        }

        public ITerator<TSource> GetIterator()
        {
            return new ArrayIterator<TSource>(Sources);
        }
    }

        private static void CoreTest()
        {
            ArrayAggregate<string> arrayAggregate = new ArrayAggregate<string>(new string[] {"cxl", "张三", "李四", "王五"});

            var iterator = arrayAggregate.GetIterator();
            while (iterator.HasNext())
            {
                iterator.MoveNext();
                Console.WriteLine(iterator.Current + "排队买好了蛋炒饭");
            }
        }

排队买蛋炒饭

posted @ 2022-01-14 20:40  icxl  阅读(17)  评论(0编辑  收藏  举报