C++設計形式編程中的迭代器形式運用解析。本站提示廣大學習愛好者:(C++設計形式編程中的迭代器形式運用解析)文章只能為提供參考,不一定能成為您想要的結果。以下是C++設計形式編程中的迭代器形式運用解析正文
迭代器形式:供給一種辦法次序拜訪一個聚合對象中個各個元素,而不裸露該對像的外部表現.
迭代器形式應當是最為熟習的形式了,最簡略的證實就是我在完成組合形式、享元形式、不雅察者形式中就直接用到了 STL 供給的迭代器來遍歷 Vector 或許 List數據構造。
迭代器形式也恰是用來處理對一個聚合對象的遍歷成績,將對聚合的遍歷封裝到一個類中停止,如許就防止了裸露這個聚合對象的外部表現的能夠。
形式的念頭:
(1)一個聚合對象,如一個列表(List)或許一個聚集(Set),應當供給一種辦法來讓他人可以拜訪它的元素,而又不須要裸露它的外部構造。
(2)針對分歧的須要,能夠還要以分歧的方法遍歷全部聚合對象,然則我們其實不願望在聚合對象的籠統層接口中充滿著各類分歧遍歷的操作。
(3)如何遍歷一個聚合對象,又不須要懂得聚合對象的外部構造,還可以或許供給多種分歧的遍歷方法,這就是迭代器形式所要處理的成績。
構造圖:
例子:
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;
}
}
}
實用場景: