博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

DesignPattern ----2(Iterator 迭代模式)

Posted on 2006-11-06 10:07  自適應軟件......  阅读(288)  评论(0编辑  收藏  举报

很久沒有來Update了,原來看到自己還有沒有完成的想法!
  今天有來寫點東西了,其實,設計模式是死的,只是在理解這些設計模式的時候,要用自己的想法應用到自己的項目,不要漂亮,只要性能和開發維護的方便,因此,對於自己,每一個階段回頭看看這些設計模式,幾乎都有新的理解!


  1    /// <summary>
  2    ///迭代子模式:迭代子模式可以順序訪問一個聚集中的元素而不必暴露聚集的內部表像。
  3    /// 多個物件聚在一起形成的總體稱之為聚集,聚集物件是能夠包容一組物件的容器物件。
  4    /// 迭代子模式將迭代邏輯封裝到一個獨立的子物件中,從而與聚集本身隔開。
  5    /// 迭代子模式簡化了聚集的介面。
  6    /// 每一個聚集物件都可以有一個或一個以上的迭代子物件,每一個迭代子的迭代狀態可以是彼此獨立的。
  7    /// 迭代演算法可以獨立於聚集角色變化。
  8    /// 
  9    /// 
 10    /// 
 11    /// 個人理解:對象化了實體,是不不用看到實體內部是怎樣,你只要輸入輸出就好了,適用與比如,關係樹,訂單,合約,等批量處理數據對象!
 12    /// </summary>

 13    class Node              //屬性類
 14    {
 15        private string name;//..還可以有很多屬性
 16
 17        public string Name
 18        {
 19            get
 20            {
 21                return name;
 22            }

 23        }

 24
 25        public Node(string s)
 26        {
 27            name = s;
 28        }

 29    }

 30
 31    class NodeCollection
 32    {
 33        private ArrayList list = new ArrayList();
 34        private int nodeMax = 0;
 35
 36
 37        public void AddNode(Node n)
 38        {
 39            list.Add(n);
 40            nodeMax += 1;
 41        }

 42
 43        public Node GetNode(int id)
 44        {
 45            return (Node)list[id];
 46        }

 47
 48        public int NodeMax()
 49        {
 50            return nodeMax;
 51        }

 52    }

 53
 54
 55    abstract class Iterator
 56    {
 57        abstract public Node Next();
 58    }

 59
 60    class ReverseIterator : Iterator
 61    {
 62        private NodeCollection nodeCollection;
 63        private int currentIndex;
 64
 65        public ReverseIterator(NodeCollection n)
 66        {
 67            nodeCollection = n;
 68            currentIndex = n - 1;
 69        }

 70
 71        public override Node Next()
 72        {
 73            if (currentIndex == -1)
 74            {
 75                return null;
 76
 77            }

 78            else
 79            {
 80                return nodeCollection.GetNode(currentIndex-1);
 81            }
            
 82        }

 83        
 84    }

 85
 86
 87    public class MyApplication
 88    {
 89        public MyApplication()
 90        {
 91            NodeCollection c = new NodeCollection();
 92            c.AddNode(new Node("tt"));
 93            c.AddNode(new Node("bb"));
 94            c.AddNode(new Node("cc"));
 95
 96
 97            ReverseIterator ri = new ReverseIterator();
 98
 99            Node n;
100            do
101            {
102                n=ri.Next();
103                if (n != null)
104                {
105                    string strPrint = n.Name;
106                }

107            }

108            while(n!=null);
109        }

110    }