#include <iostream>
#include <string>
template <typename T>
class Iterator {
public:
virtual ~Iterator(){};
virtual bool hasNext() = 0;
virtual T *next() = 0;
};
template <typename T>
class Aggregate {
public:
virtual ~Aggregate(){};
virtual Iterator<T> *iterator() = 0;
};
class Book {
private:
std::string name;
public:
Book(){};
Book(std::string name);
~Book(){};
std::string getName();
friend std::ostream &operator<<(std::ostream &s, Book *b);
};
template <typename T>
class TShelf : Aggregate<T> {
private:
T **t_s;
int maxsize;
int last;
public:
TShelf<T>(int maxsize);
~TShelf(); /* ----------------here---------------- */
T *getAt(int index);
void append(T *book);
int getLength();
Iterator<T> *iterator();
};
template <typename T>
class TShelfIterator : public Iterator<T> {
private:
TShelf<T> *tShelf;
int index;
public:
TShelfIterator<T>(TShelf<T> *t_shelf);
~TShelfIterator(){}; /* ----------------here---------------- */
bool hasNext();
T *next();
};
Book::Book(std::string name) { this->name = name; }
std::string Book::getName() {return this->name; }
std::ostream &operator<<(std::ostream &s, Book *b) {
s << b->name;
return s;
}
template <typename T> TShelf<T>::TShelf(int maxsize) {
this->t_s = new T* [maxsize];
this->maxsize = maxsize;
this->last = 0;
}
template <typename T> TShelf<T>::~TShelf() { delete [] (this->t_s); } /* ----------------here---------------- */
template <typename T> T *TShelf<T>::getAt(int index) { return this->t_s[index]; }
template <typename T> void TShelf<T>::append(T *t) {
if (last < maxsize) {
this->t_s[last] = t;
this->last++;
}
}
template <typename T> int TShelf<T>::getLength() { return this->last; }
template <typename T> Iterator<T> *TShelf<T>::iterator() { return new TShelfIterator<T>(this); }
template <typename T> TShelfIterator<T>::TShelfIterator(TShelf<T> *tShelf) {
this->tShelf = tShelf;
this->index = 0;
}
template <typename T> bool TShelfIterator<T>::hasNext() {
if (this->index < this->tShelf->getLength()) return true;
else return false;
}
template <typename T> T *TShelfIterator<T>::next() {
T *t = this->tShelf->getAt(index);
index++;
return t;
}
int main() {
TShelf<Book> *tShelf = new TShelf<Book>(4);
tShelf->append(new Book("A"));
tShelf->append(new Book("BB"));
tShelf->append(new Book("CCC"));
tShelf->append(new Book("DDDD"));
Iterator<Book> *it = tShelf->iterator();
while (it->hasNext()) {
Book *book = it->next();
std::cout << book << std::endl;
}
delete it;
delete tShelf;
return 0;
}
/* end */