Iterator 提供一种方法顺序访问一个对象中各个元素,而又不需要暴露该对象的内部表示...

it2022-05-09  29

Aggregate  1using System; 2using System.Collections.Generic; 3using System.Text; 4 5namespace Gof.Test.Iterator 6{ 7    public interface Aggregate 8    { 9        Iterator CreateIterator();10    }11}12 ConcreteAggregate  1using System; 2using System.Collections.Generic; 3using System.Text; 4 5namespace Gof.Test.Iterator 6{ 7    public class ConcreteAggregate : Aggregate 8    { 9        Aggregate 成员#region Aggregate 成员1011        public Iterator CreateIterator()12        {13            return new ConcreteIterator(this);14        }1516        #endregion1718        private System.Collections.ArrayList items = new System.Collections.ArrayList();1920        public int Count21        {22            get23            {24                return items.Count;25            }26        }2728        public object this[int index]29        {30            get31            {32                return (object)items[index];33            }34            set35            {36                items.Insert(index, value);37            }38        }39    }40} Iterator  1using System; 2using System.Collections.Generic; 3using System.Text; 4 5namespace Gof.Test.Iterator 6{ 7    public interface Iterator 8    { 9        object First();10        object Next();11        bool isDone();12        object Current();13    }14} ConcreteIterator  1using System; 2using System.Collections.Generic; 3using System.Text; 4 5namespace Gof.Test.Iterator 6{ 7    public class ConcreteIterator : Iterator 8    { 9        private ConcreteAggregate concreteAggregate;10        private int current = 0;1112        public ConcreteIterator(ConcreteAggregate t)13        {14            concreteAggregate = t;  15        }1617        Iterator 成员#region Iterator 成员1819        public object First()20        {21            return concreteAggregate[0];22        }2324        public object Next()25        {26            if (current < concreteAggregate.Count - 1)27            {28                return concreteAggregate[current++];29            }30            return null;31        }3233        public bool isDone()34        {35            return current >= concreteAggregate.Count ? true : false;36        }3738        public object Current()39        {40            return concreteAggregate[current];41        }4243        #endregion44    }45} 客户代码  1            ConcreteAggregate a = new ConcreteAggregate(); 2            a[0= "0"; 3            a[1= "00"; 4            a[2= "000"; 5            a[3= "0000"; 6            a[4= "00000"; 7            a[5= "000000"; 8 9            ConcreteIterator i = new ConcreteIterator(a);1011            Console.WriteLine("begin");1213            object item = i.First();1415            while (item != null)16            {17                Console.WriteLine(item);18                item = i.Next();19            }2021            Console.ReadKey();

转载于:https://www.cnblogs.com/nanshouyong326/archive/2007/01/17/622518.html


最新回复(0)