Iteratorパターンの例です。
気が向けばそのうち解説文を書きます。
一般的なIteratorパターンの実装例
package sample.design_pattern;
public abstract boolean hasNext();
public abstract void next();
public abstract Object getValue
(); }
interface Aggregate {
}
private int value;
this.value = value;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
private ElementList list;
private int index;
this.list = list;
this.index = 0;
}
public boolean hasNext() {
return (list.getLastNum() > index) ? true : false;
}
public void next() {
++index;
}
return list.getValueAt(index);
}
}
class ElementList implements Aggregate {
private int last = 0;
public ElementList(int count) {
}
list[last++] = element;
}
public Element getValueAt
(int index
) { return list[index];
}
public int getLastNum() {
return last;
}
}
}
public class IteratorPatternTest {
public static void main
(String[] args
) { ElementList list = new ElementList(5);
for (int i = 0; i < 5; ++i) {
}
for (Iterator it
= list.
iterator(); it.
hasNext(); it.
next()) { }
}
}
※ 暫定版
#include <iostream>
using namespace std;
template <typename T>
struct iteratable {
virtual ~iteratable() {}
virtual const bool has_next() = 0;
virtual void next() = 0;
virtual const T get_value() = 0;
};
template <typename Iterator>
struct aggregatable {
virtual ~aggregatable() {}
virtual Iterator iterator_begin() = 0;
};
template <typename T, typename List>
class element_iterator : public iteratable<T> {
const List &list_;
size_t index_;
public :
element_iterator(const List &list) : list_(list), index_(0) {}
const bool has_next() {
return (list_.get_last_num() > index_) ? true : false;
}
void next() { ++index_; }
const T get_value() { return list_.get_value_at(index_); }
};
template <typename T>
class element_list : public aggregatable<element_iterator<T, element_list<T> > > {
T *plist_;
size_t last_;
public :
typedef element_iterator<T, element_list<T> > iterator;
element_list(const size_t count) : plist_(new T[count]), last_(0) {
}
~element_list() {
delete [] plist_;
}
void add(const T val) {
plist_[last_++] = val;
}
const T get_value_at(const size_t index) const {
return plist_[index];
}
const size_t get_last_num() const {
return last_;
}
element_iterator<T, element_list<T>> iterator_begin() {
return element_iterator<T, element_list<T> >(*this);
}
};
int main() {
element_list<int> list(5);
for (int i = 0; i < 5; ++i) {
list.add(i);
}
element_list<int>::iterator it = list.iterator_begin();
for ( it; it.has_next(); it.next()) {
cout << it.get_value() << endl;
}
}
最終更新:2008年09月10日 10:12