Skip to content

Instantly share code, notes, and snippets.

@yknishidate
Created March 4, 2022 03:15
Show Gist options
  • Save yknishidate/d0f4138298c1424d04d7a95d8aca56bb to your computer and use it in GitHub Desktop.
Save yknishidate/d0f4138298c1424d04d7a95d8aca56bb to your computer and use it in GitHub Desktop.
#include <iostream>
class Monster
{
public:
virtual void attack() = 0;
};
class Ghost : public Monster
{
public:
void attack() override { std::cout << "Ghost attacked!" << std::endl; }
};
class Demon : public Monster
{
public:
void attack() override { std::cout << "Demon attacked!" << std::endl; }
};
class Spawner
{
public:
virtual ~Spawner() {}
virtual Monster *spawnMonster() = 0;
};
template <class T>
class SpawnerFor : public Spawner
{
public:
Monster *spawnMonster() override { return new T(); }
};
int main()
{
Spawner *ghostSpawner = new SpawnerFor<Ghost>();
Spawner *demonSpawner = new SpawnerFor<Demon>();
Monster *ghost = ghostSpawner->spawnMonster();
Monster *demon = demonSpawner->spawnMonster();
ghost->attack();
demon->attack();
}
@yknishidate
Copy link
Author

Game Programming Patterns

  • プロトタイプパターンといいつつ、C++であればtemplateを使う方が良い
  • templateなどがサポートされていない環境、たとえばjsonでデータを保存するような場合はいまだに価値がある

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment