I currently have two singletons that are unfortunately depending on one another.
I'm following SDL Game Development by Shaun Mitchell, so please don't choke me out for using singletons, I'm just following the book. I want to clean up my includes, but this dependency is giving me problems.
I have one singleton called Game, typedef'd as TheGame, that has a bool that holds it's running state when this bool goes false it ends the game loop in main. I also have an InputHandler Singleton, typedef'd as TheInputHandler that has an event handler that changes the bool from TheGame when the SDL_Quit event is seen. The problem is that Game has to call TheInputHandler to initialize the controls. How do I break this circular dependency?
As I said I know my includes are a mess, but here's the relevant parts of the code. I set the really important bits to bold.
For the record, all of my code does compile and it runs as I expect it to. I'm just leary of having co-dependent classes.
In my opinion, both "TheGame" and (at least) "TheInputHandler" shouldn't exist -- it seems like an artifact of trying to shoehorn object-orientation into the problem.
Singletons are often named antipatterns. That's because they abuse the nature of classes --- classes are intended to represent distinct variants of the same kind of object --- not global state.
The only purpose of (the only) InputHandler object is as a container for names dealing with input and reacting to them. Use a namespace instead, and move the information about how you react to input away.
If there were simply functions in place of the class garbage, we might more easily realize that getting input has nothing to do with what the game does with that input -- and the code that gets the input shouldn't care at all about the structure of the game at all -- those concerns are totally unrelated.
I understand that singletons are not generally liked for the reasons you're stating. I'm still learning how to structure larger programs and I currently don't have the knowlege or experience to argue against or deviate from the author of this book's design. Where do you gain knovlege about things like this besides from reading someone elses work? I find so many programming books with poor examples and designs. How do you learn the proper way with so many bad examples out there?