Ubiquitous Iterator <?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />
This article is contributed by Wang HaiLong.
Preface
As one of 23 basic Design Patterns, Iterator seems to appear everywhere. This article discusses some scenarios where Iterator Pattern is applied, including STL, Collection in Java, IEnumXXXX interface in COM, IRowset interface in OLE DB, RecordSet Object in <?xml:namespace prefix = st1 ns = "urn:schemas-microsoft-com:office:smarttags" /><city><place><span lang="EN-US" style="FONT-FAMILY: 'Courier New'">ADO</span></place></city>, ResultSet in JDBC, Cursor in Oracle's SQL/PL.
Iterator Concept
Iterator Pattern separates the iteration operation from Container/Collection. To satisfy Iterator Pattern, there must be two Objects: a Container and its Iterator.
The aim of Iterator Pattern is to unify the way of iterating a Container, in spite of what kiand of data is put in the Container, and how the Container's internal structure is implemented.
The following is a simple example imitating STL.
// SimpleArray.cpp
template<typename T>
class SimpleArray
{
T data[100];
public:
class Iterator
{
SimpleArray<T>* m_pArray;
int m_iCurrentIndex;
friend class SimpleArray<T>;
public:
Iterator( SimpleArray<T>* pArray = 0) : m_pArray(pArray)
{
}
void Reset()
{
m_iCurrentIndex = 0;
}
T operator *()
{
return m_pArray->data[m_iCurrentIndex];
}
void operator --()
{
m_iCurrentIndex--;
}
void operator ++()
{
m_iCurrentIndex++;
}
bool operator !=(const Iterator& another)
{
if( m_pArray != another.m_pArray )
return true;
if( m_iCurrentIndex != another.m_iCurrentIndex )
return true;
return false;
}
};
Iterator begin()
{
Iterator it(this);
it.m_iCurrentIndex = 0;
return it;
}
Iterator end()
{
Iterator it(this);
it.m_iCurrentIndex = 100;
return it;
}
friend class Iterator;
};
template<class Container>
int sum(Container & con)
{
Container::Iterator it;
int total = 0;
for( it = con.begin(); it != con.end(); it++)
{
total += *it;
}
return total;
}
void test()
{
SimpleArray<int> con;
int total = sum(con);
}
If later we don't want to use the SimpleArray any more, we can change the test function as below.
#include <set>
void test()
{
set<int> con;
int total = sum(con);
}
Hence the separation of data structure and algorithm.
STL
The above example demonstrates the usage of STL and how to write STL-style programs. Now lets discuss some STL features in more depth.
As we have seen, algorithms can exist independent of data structure using STL. The key concept is "Function Object", which is detailed in chapter 21 "STL Algorithms" of <<Thinking in C++>>.
Now lets take a glimpse of what is a "Function Object".
Take the method "sort" of list in STL, for example.
template<class Pred> void sort(greater<T> pr);
The parameter pr inherits the "Function Object" greater and is also a "Function Object".
And the implementation likely takes the following shape.
struct CCompareTwoItem : public std::greater< T >
{
public:
bool operator()( T item1, T item2 )
{
}
};
Iterator in Java and C++
Enumeration interface and Iterator interface( in Java2) are self-explanatory. What is more, sub view is supported in Java.
similar effect can be approximated through filter iterator.
IEnumXXXX interface in COM
The definition of IEnumXXXX is:
Interface IEnumXXX : IUnknown
{
virtual HRESULT Next(unsigned long celt, XXXX* rgelt, unsigned long * pceltFetched) = 0;
virtual HRESULT Skip(unsigned long celt) = 0;
virtual HRESULT Reset() = 0;
virtual HRESULT Clone(IEnumXXXX** ppeunm);
}
An good example is "Connectable Objects" in COM.
interface IConnectionPoint : IUnknown
{
HRESULT GetConnectionInterface(IID* pIID);
HRESULT GetConnectionPointContainer(IConnectionPointContainer** ppCPC);
HRESULT Advise(IUnknown* pUnk, DWORD* pdwCookie);
HRESULT Unadvise(DWORD dwCookie);
HRESULT EnumConnections(IenumConnections** ppEnum);
}
interface IconnectionPointContainer : IUnknown
{
HRESULT EnumConnectionPoints(IEnumConnectionPoints** ppEnum);
HRESULT FindConnectionPoint(REFIID riid, IConnectionPoint** ppCP);
}
interface IEnumConnectionPoints
{
HRESULT Next(ULONG cConnections, IConnectionPoint** rgpcn,ULONG* pcFetched);
HRESULT Skip(ULONG cConnections);
HRESULT Reset(void);
HRESULT Clone(IEnumConnectionPoints** ppEnum);
}
IConnectionPointContainer holds IConnectionPoint and IConnectionPointContainer's method EnumConnectionPoints returns an IEnumConnectionPoints which can iterate the IConnectionPointContainer to get every IConnectionPoint.
IRowset interface in OLE DB
IRowset method description:
AddRefRows Adds a reference count to an existing row handle.
GetData Retrieves data from the rowset's copy of the row.
GetNextRows Fetches rows sequentially, remembering the previous position.
ReleaseRows Releases rows.
RestartPosition Repositions the next fetch position to its initial position; that is, its position when the rowset was first created.
The definition of ICommand::Excute is:
HRESULT Execute (IUnknown* pUnkOuter, REFIID riid, DBPARAMS* pParams, LONG* pcRowsAffected, IUnknown** ppRowset);
This method returns an IRowset interface which can iterate through the result of "Excute".
RecordSet Object in <city><place><span lang="EN-US" style="FONT-FAMILY: 'Courier New'">ADO</span></place></city>
The follow text is extracted from <city><place><span lang="EN-US" style="FONT-FAMILY: 'Courier New'">ADO</span></place></city> help.
A Recordset object represents the entire set of records from a base table or the results of an executed command. At any time, the Recordset object only refers to a single record within the set as the current record.
Using the Open method on a Recordset object opens a cursor that represents records from a base table or the results of a query.
Ways to get RecordSet Object include:
On a Command object: Set recordset = command.Execute(RecordsAffected, Parameters, Options)
On a Connection object: Set recordset = connection.Execute(CommandText, RecordsAffected, Options)
ResultSet in JDBC
Connection Con = getConnection();
Statement stmt = con.createStatement(ResultSet.TYPE_SCROOL_INSENTIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet rs = stmt.excuteQuery(query);
While(rs.next()){c};
Cursor in Oracle's SQL/PL
We can look on Cursor as a forward-only iterator.
Appendix
Some great books about Design Patterns:
<<Design Patterns>> by <city><place><span lang="EN-US" style="FONT-FAMILY: 'Courier New'">Zurich</span></place></city>, <city><place><span lang="EN-US" style="FONT-FAMILY: 'Courier New'">Sydney</span></place></city>, <city><place><span lang="EN-US" style="FONT-FAMILY: 'Courier New'">Urbana</span></place></city>, <city><place><span lang="EN-US" style="FONT-FAMILY: 'Courier New'">Hawthorne</span></place></city>;
<<Thinking in C++>> and <<Thinking in Java >> by Bruce Eckel;
<<The Design Patterns Java Companion>> by James W. Cooper.
分享到:
相关推荐
Advances in Computer Science and Ubiquitous Computing
Stefan Poslad编著的Ubiquitous Computing原版PDF书籍 下载于http://onlinelibrary.wiley.com 书籍的信息请参见http://www.elec.qmul.ac.uk/people/stefan/ubicom
Abstract The vision of ubiquitous computing is becoming a reality thanks to the advent of portable devices and the advances in wireless networking technologies. It aims to facilitate user tasks ...
B-trees have become, de facto, a standard for file organization. File indexes of users, dedicated database systems, and general-purpose access methods have all been proposed and nnplemented using B-...
Lecture Notes of the Institute for Computer Sciences, Social Informatics and Telecommunications Engineering
The audience for the books in LNEE consists of advanced level students,researchers, and industry professionals working at the forefront of their fi elds.Much like Springer's other Lecture Notes ...
普适计算与移动计算教材Ubiquitous Computing PPT slides
内容很详细,包括各个平台的开发语言都列出来,不过没有源码。有兴趣的朋友可以参考这个survey上给出的项目自己再去细细研究,读Paper,看源码。
Asterisk with IPv6 Seamless and Ubiquitous VoIP
The authors identify two key characteristics of ubiquitous computing systems, physical integration and spontaneous interoperation. They examine how these properties affect the design of ubicomp ...
商业普适计算(Ubiquitous Computing for Business) 在全年365天、每周七天、每天廿四小时全球范围内找到新市场、建立更好的业务、获得客户 (Find New Markets, Create Better Businesses, and Reach Customers ...
complex analysis, and harmonic analysis, as well as a ubiquitous factor in the description and elucidation of problems in mathematical physics. This work is intended to provide a course of study of ...
While this edition of this book is in English, and English remains the number-one technical language worldwide, it is far from the only one. Most end users would rather have an application that has ...
Evolution Toward Artificial Intelligence of Things Under 6G Ubiquitous⁃X.pdf
Parquet has also recently emerged as a new way to store data in HDFS—its columnar format can yield both space and time efficiencies in your data pipelines, and it’s quickly becoming the ubiquitous ...
We are in the era of ubiquitous computing in which the use and development of Radio Frequency Identification (RFID) is becoming more widespread. RFID systems have three main components: readers, tags,...
PID control is ubiquitous. While simple in theory, design and implementation of PID controllers can be difficult and time consuming in practice. PID control involves several tasks that include:
MATLAB.-.A.Ubiquitous.Tool.for.the.Practical.Engineer
Electromagnetic radiation fields are ubiquitous in modern society. It is well known that long-term exposure in strong fields can result in bad effects to health due to some unknown mechanism. There ...
使用智能手机和智能手表进行直观且无处不在的发热监测_Intuitive and Ubiquitous Fever Monitoring Using Smartphones and Smartwatches.pdf