In a game, many entities should be updated every frame. Im toying with different design patterns to achieve this. Up until now, Ive had a singleton manager class to which every Logic instance is added. But Im considering the following, a static list in the Logic class itself. This is nice since it would remove a class from the project. ‘Engine’ in this example would be the master class calling the update_all.
class Logic { public: Logic() { all.push_back(this); } virtual ~Logic() { all.erase(this); } virtual void update(float deltatime) = 0; private: friend Engine; static std::list<Logic*> all; static void update_all(float deltatime) { for (std::list::iterator i = all.begin(); i!=all.end(); ++i) (*i)->update(deltatime); } };
- Does this pattern have a name?
- Do you consider this a nicer approach than a singleton manager class?
- Any other comments or caveats?
First, you need to use
remove()instead oferase()(the latter would need an iterator as argument)If you use a slightly different loop like
you can even overcome the problem siukurnin mentioned (deletion of a Logic object during update()).
list::remove()doesn’t invalidate iterators except of the ones pointing to the removed element.Apart from this, I also vote for this being a variation of the singleton pattern. And I would suggest for keeping the original solution with a separate management class, just in case you want to have to have two loops with different delta times or explicit multithread support (different Logic objects on different threads) or whatever in the future.
In my opinion this is a general advantage of the singleton class over static methods (which you could always use): You can easily multiply your functionality if you want to do so in the future …