#include <iostream>
#include <string>
class Iterator {
public:
virtual ~Iterator(){};
virtual bool hasNext() = 0;
virtual void *next() = 0;
};
class Aggregate {
public:
virtual ~Aggregate(){};
virtual Iterator *iterator() = 0;
/* virtual void delete_iterator(Iterator *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);
};
class BookShelf : Aggregate {
private:
Book **books;
int maxsize;
int last;
public:
BookShelf(int maxsize);
~BookShelf();
Book *getBookAt(int index);
void appendBook(Book *book);
int getLength();
Iterator *iterator();
/* void delete_iterator(Iterator *); */
};
class BookShelfIterator : public Iterator {
private:
BookShelf *bookShelf;
int index;
public:
BookShelfIterator(BookShelf *bookShelf);
~BookShelfIterator(){};
bool hasNext();
void *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;
}
/*-----------------------------------------------*/
BookShelf::BookShelf(int maxsize) {
this->books = new Book* [maxsize];
this->maxsize = maxsize;
this->last = 0;
}
BookShelf::~BookShelf() { delete [] (this->books); }
Book *BookShelf::getBookAt(int index) { return this->books[index]; }
void BookShelf::appendBook(Book *book) {
if (last < maxsize) {
this->books[last] = book;
this->last++;
}
}
int BookShelf::getLength() { return this->last; }
Iterator *BookShelf::iterator() { return new BookShelfIterator(this); }
/* void BookShelf::delete_iterator(Iterator *iterator) { delete iterator; } */
/*-----------------------------------------------*/
BookShelfIterator::BookShelfIterator(BookShelf *bookShelf) {
this->bookShelf = bookShelf;
this->index = 0;
}
bool BookShelfIterator::hasNext() {
if (this->index < bookShelf->getLength()) return true;
else return false;
}
void *BookShelfIterator::next() {
Book *book = bookShelf->getBookAt(index);
index++;
return (void *)book;
}
int main() {
BookShelf *bookShelf = new BookShelf(4);
bookShelf->appendBook(new Book("A"));
bookShelf->appendBook(new Book("BB"));
bookShelf->appendBook(new Book("CCC"));
bookShelf->appendBook(new Book("DDDD"));
Iterator *it = bookShelf->iterator();
while (it->hasNext()) {
Book *book = (Book *)it->next();
std::cout << book << std::endl;
}
delete it;
/* bookShelf->delete_iterator(it); */
delete bookShelf;
return 0;
}
/* end */