Skip to content

Instantly share code, notes, and snippets.

@muaddib1971
Last active March 25, 2023 12:02
Show Gist options
  • Save muaddib1971/83789b9a474dc21e53f111e0577a9216 to your computer and use it in GitHub Desktop.
Save muaddib1971/83789b9a474dc21e53f111e0577a9216 to your computer and use it in GitHub Desktop.
a menu using the command pattern
#include <iostream>
#include <string>
class menu_action {
public:
virtual bool operator() ()const = 0;
};
class play_game : public menu_action {
public:
virtual bool operator() () const override{
std::cout << "playing the game" << std::endl;
return true;
}
};
class student_information : public menu_action {
public:
virtual bool operator() () const override {
std::cout << "student information" << std::endl;
return true;
}
};
class quit_game : public menu_action{
public:
virtual bool operator() () const override {
std::cout << "quitting" << std::endl;
return false;
}
};
class menu_item{
menu_action * action;
std::string text;
public:
const std::string& get_text() { return text;}
void set_text(const std::string& newtext){ text = newtext;}
const menu_action& get_action(){return *action;}
void set_action(menu_action * const newaction) { action = newaction; }
~menu_item(){ delete action; }
};
int main() {
menu_item menu[3] = {};
menu_action * actions[3] = {new play_game(), new student_information(), new quit_game()};
std::string texts[3] = {"play the game", "student informtion", "quit"};
for(int count =- 0; count < 3; ++count) {
menu[count].set_text(texts[count]);
menu[count].set_action(actions[count]);
}
bool keepgoing = true;
do {
std::cout << "menu" << std::endl;
std::cout << "----" << std::endl;
for(int count = 0; count < 3 ; ++count) {
std::cout << count + 1 << ") " << menu[count].get_text() << std::endl;
}
int input{};
std::cin >> input;
keepgoing = menu[input-1].get_action()();
}
while(keepgoing);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment