结构:
意图:
迭代器模式提供一种方法顺序访问一个聚合对象中各个元素,而又不暴露该对象的内部表示。
适用性:
(1)访问一个聚合对象的内部而不暴露它的内部表示。
(2)支持聚合对象的多种遍历。
(3)为遍历不同的聚合结构提供统一的接口,即支持多态迭代。
举例: (1)C++标准模板库是迭代器模式一个极为成功的应用。
示例:
- // Iterator
- // Intent: "Provide a way to access the elements of an aggregate object
- // sequentially without exposing its underlying representation".
- //提供一种方法,顺序访问一个聚合对象中的各个元素,而又不暴露该对象的内部表示。
- // For further information, read "Design Patterns", p257, Gamma et al.,
- // Addison-Wesley, ISBN:0-201-63361-2
- /* Notes:
- * Here wish wish to separate node traversal from the nodes themselves.
- * STL in ISO C++ is a highly successful application of this pattern.
- * Generic programming is a great way to implement iterators. As this is
- * not yet in C#, we use inheritance.
- * 将节点和对节点的遍历相分离。
- * C++标准模板库是这种模式的一个很成功的应用。泛型编程是迭代器实现模式模式的上佳方式
- */
- namespace Iterator_DesignPattern
- {
- using System;
- using System.Collections;
- class Node //elements in aggregate
- {
- private string name;
- public string Name
- {
- get
- {
- return name;
- }
- }
- public Node(string s)
- {
- name = s;
- }
- }
- class NodeCollection //aggregate
- {
- private ArrayList list = new ArrayList();
- private int nodeMax = 0;
- // left as a student exercise - implement collection
- // functions to remove and edit entries also
- public void AddNode(Node n)
- {
- list.Add(n);
- nodeMax++;
- }
- public Node GetNode(int i)
- {
- return ((Node)list[i]);
- }
- public int NodeMax
- {
- get
- {
- return nodeMax;
- }
- }
- }
- /*
- * The iterator needs to understand how to traverse the collection
- * It can do that as way it pleases - forward, reverse, depth-first,
- */
- abstract class Iterator //abstract Iterator
- {
- abstract public Node Next();
- }
- class ReverseIterator : Iterator //concrete Iterator
- {
- private NodeCollection nodeCollection;
- private int currentIndex;
- public ReverseIterator(NodeCollection c)
- {
- nodeCollection = c;
- currentIndex = c.NodeMax - 1; // array index starts at 0!
- }
- // note: as the code stands, if the collection changes,
- // the iterator needs to be restarted
- override public Node Next()
- {
- if (currentIndex == -1)
- return null;
- else
- return (nodeCollection.GetNode(currentIndex--));
- }
- }
- ///
- /// Summary description for Client.
- ///
- public class Client
- {
- public static int Main(string[] args)
- {
- NodeCollection c = new NodeCollection();
- c.AddNode(new Node("first"));
- c.AddNode(new Node("second"));
- c.AddNode(new Node("third"));
- // now use iterator to traverse this
- ReverseIterator i = new ReverseIterator(c);
- // the code below will work with any iterator type
- Node n;
- do
- {
- n = i.Next();
- if (n != null)
- Console.WriteLine("{0}", n.Name);
- } while (n != null);
- Console.Read();
- return 0;
- }
- }
- }
如下是《大话设计模式》中的一个例子,稍作改变:
阅读(698) | 评论(0) | 转发(0) |