Created
March 16, 2016 14:32
-
-
Save shrddr/31abf56704c4ccdca9ce to your computer and use it in GitHub Desktop.
c++ factory
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <vector> | |
class GameState | |
{ | |
public: | |
static GameState* create(int choice); | |
virtual void invoke() = 0; | |
}; | |
class Menu : public GameState | |
{ | |
public: | |
void invoke() { std::cout << "menu invoke\n"; } | |
}; | |
class Tuner : public GameState | |
{ | |
public: | |
void invoke() { std::cout << "tuner invoke\n"; } | |
}; | |
class Game : public GameState | |
{ | |
public: | |
void invoke() { std::cout << "game invoke\n"; } | |
}; | |
GameState* GameState::create(int choice) | |
{ | |
if (choice == 1) | |
return new Menu; | |
if (choice == 2) | |
return new Tuner; | |
if (choice == 3) | |
return new Game; | |
} | |
int main() | |
{ | |
int choice; | |
std::vector<GameState*> states; | |
while (true) | |
{ | |
std::cin >> choice; | |
if (choice == 0) | |
break; | |
states.push_back(GameState::create(choice)); | |
} | |
for (auto s : states) s->invoke(); | |
for (auto s : states) delete s; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment