Skip to content

Instantly share code, notes, and snippets.

@shrddr
Created March 16, 2016 14:32
Show Gist options
  • Save shrddr/31abf56704c4ccdca9ce to your computer and use it in GitHub Desktop.
Save shrddr/31abf56704c4ccdca9ce to your computer and use it in GitHub Desktop.
c++ factory
#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