C++设计模式编程中的迭代器模式应用解析
发布时间:2020-12-16 05:36:29 所属栏目:百科 来源:网络整理
导读:迭代器模式:提供一种方法顺序访问一个聚合对象中个各个元素,而不暴露该对像的内部表示. 迭代器模式应该是最为熟悉的模式了,最简单的证明就是我在实现组合模式、享元模式、观察者模式中就直接用到了 STL 提供的迭代器来遍历 Vector 或者 List数据结构。 迭
迭代器模式:提供一种方法顺序访问一个聚合对象中个各个元素,而不暴露该对像的内部表示. 迭代器模式应该是最为熟悉的模式了,最简单的证明就是我在实现组合模式、享元模式、观察者模式中就直接用到了 STL 提供的迭代器来遍历 Vector 或者 List数据结构。 迭代器模式也正是用来解决对一个聚合对象的遍历问题,将对聚合的遍历封装到一个类中进行,这样就避免了暴露这个聚合对象的内部表示的可能。 模式的动机: 结构图: 例子: namespace Iterator_DesignPattern { using System; using System.Collections; class Node { private string name; public string Name { get { return name; } } public Node(string s) { name = s; } } class NodeCollection { 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 public Node Next(); } class ReverseIterator : 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> /// Summary description for Client. /// </summary> 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); return 0; } } } 适用场景:
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |