iterator.h
#ifndef _ITERATOR_H_
#define _ITERATOR_H_ class Iterator {
public:
virtual bool has_next() = ;
virtual void *next() = ;
};
#endif
menu.h
#ifndef _MENU_H_
#define _MENU_H_ class Menu {
public:
virtual Iterator *get_iterator() = ;
virtual ~Menu() {};
};
#endif
diner_menu.h
#ifndef _DINER_MENU_H_
#define _DINER_MENU_H_ #include "menu_item.h"
#include "iterator.h"
#include <vector>
#include "menu.h" class DinerMenu : public Menu {
public:
void add_item(const std::string& name,
const std::string& description,
bool vegetarian,
double price) {
menu_items.push_back( MenuItem(name, description, vegetarian, price) );
} DinerMenu() : iterator( *this ) {
add_item("diner name_1", "descrption_1", true, 4.5);
add_item("diner name_2", "descrption_2", true, 6.2);
add_item("diner name_3", "descrption_3", false, 3.5);
} Iterator *get_iterator() {
return &iterator;
}
private:
class _Iterator : public Iterator {
private:
DinerMenu &menu;
int pos;
public:
_Iterator( DinerMenu &_menu) : pos(), menu(_menu) {}
bool has_next() { return pos < menu.menu_items.size(); }
void* next() {
return &(menu.menu_items[pos++]);
}
} iterator; std::vector<MenuItem> menu_items;
};
#endif
pancake_house_menu.h
#ifndef _PANCAKE_HOUSE_MENU_H_
#define _PANCAKE_HOUSE_MENU_H_ #include "menu_item.h"
#include "iterator.h"
#include "menu.h" class PancakeHouseMenu : public Menu {
public:
void add_item(const std::string& name,
const std::string& description,
bool vegetarian,
double price) {
if ( item_num < MAX_ITEMS ) {
menu_items[item_num++] = new MenuItem( name, description, vegetarian, price );
}
} PancakeHouseMenu() : item_num(), iterator(*this) {
add_item("name_1", "descrption_1", true, 4.5);
add_item("name_2", "descrption_2", true, 6.2);
add_item("name_3", "descrption_3", false, 3.5);
} ~PancakeHouseMenu() {
for ( int i = ; i < item_num; i++ ) {
delete menu_items[i];
}
} Iterator *get_iterator() {
return &iterator;
} private:
class _Iterator : public Iterator {
private:
PancakeHouseMenu &menu;
int pos;
public:
_Iterator( PancakeHouseMenu &_menu) : pos(), menu(_menu) {}
bool has_next() { return pos < menu.item_num; }
void* next() {
return menu.menu_items[pos++];
}
} iterator; const static int MAX_ITEMS = ;
MenuItem *menu_items[MAX_ITEMS];
int item_num;
};
#endif
main.cpp
#include "pancake_house_menu.h"
#include "diner_menu.h"
#include <iostream> int main() {
Menu * menus[] = { new PancakeHouseMenu, new DinerMenu };
for ( int i = ; i < sizeof(menus)/sizeof(menus[]); i++ ) {
Iterator *iterator = menus[i]->get_iterator();
while ( iterator->has_next() ) {
MenuItem *menu_item = (MenuItem *)iterator->next();
std::cout << menu_item->get_name() << " "
<< menu_item->get_description() << " "
<< menu_item->is_vegetarian() << " "
<< menu_item->get_price() << std::endl;
}
delete menus[i];
}
}