mardi 12 octobre 2021

Singleton vs passing a reference to it and storing it in classes

I've got this quarrel with a friend: he says that I should use a singleton, but I read everywhere that singletons are rarely a good idea.

My use case is that I'm implementing this game engine (too little experience with that, so I'm trying to learn one way or the other) where I've got a class Application, for instance:

class Application{
private:
    SomeClass1 someClass1;
    SomeClass2 someClass2;
    
  ...
}
class SomeClassN{
private:
    Application& app;
    SomeClass14 someClass14 // meaning that Application& will be needed deeply into the tree of "components"
    ...
}

It should be added that not all classes will be of type SomeClassX (not all classes will need to contain Application&).

My friend tells me to make Application a singleton, while I just prefer passing it and storing it. Actually I would create a base class:

class ApplicationContainee {// temporary name, please kindly suggest a correct name
protected:
    Application& app;
}
class SomeClassX : ApplicationContainee {

}

I'm afraid that even this approach might be disastrous or maybe equivalent of having a singleton.

Summing up:

  • Singleton vs above strategy vs other
  • In case the above strategy is decent, how should I really name ApplicationContainee?

Aucun commentaire:

Enregistrer un commentaire