So I have a player class in my game. Logically there only needs to be one player object (single player) But a lot of different classes need access to the player object. (ie, maps needs to know were player is, as does camera and enemies need to interact with the player, etc).
I have a couple of options.
Either I could pass this player object around to everything that needs it which is cumbersome. (Dependency injection I think it’s called)
Just make it public static.
Make it a singleton.
What are the pros/cons of each?
I would not use a Singleton or static variable here and instead would hand a
Playerinstance to the classes that need it via setters. If you only need one player instance – only callnew Player()once 🙂See my take on Singletons here. Short summary: their typical misuse (avoiding “cumbersome” setters) violates OO and lowers design quality.
Static variables are cut from the same cloth as Singletons, along with the Monostate (non-static getters, static data, constructor is the “factory”). Avoid them. Consider if you made everything static: player, map, camera, enemies, etc. You would avoid a lot of “cumbersome” setters. But is it OO? When you finish your game can you reuse your pathfinding algorithms, AI algorithms, etc. on another game, or do they have too many global variables (Singletons et al) specific to your current game burned into them forever?