I've just begun working on my game and I don't know how to organize my game in separate classes, because I need some variables/methods to be available to every class. I have a screen manager class and some screen classes which inherit a base screen class. But I can't access the screen manager's methods without making it a singleton, and I would like to avoid this solution. And I would like some game variables or methods to be available from any other class, but I can't do it without making them static. Let's say I have variable which stores the game difficulty throughout the game screens. If I would like to implement such a thing I would need to make it static in the Game1 class. Short story, I don't know how to make methods/variables global without making them static.
|
|
In case your reason for not making them static is that you see a possibility for needing to have several instances of them in the future then I think using singletons is an elegant solution. Assuming that you might need to make several instances of these classes in the future you could store a reference to them in a wrapper class and send this as parameter in the constructor of those classes that need them. Alternatively you could send references as parameters to whatever methods need them (like draw or update or whatever). However having a lot of circular references might be a "bad smell" ie a warning sign that somthing needs to be redesigned... |
|||
|
|
There is often a temptation to make some parts of your application globally accessible, most commonly by making them static or by using the Singleton pattern or the Registry pattern. Do not follow that temptation. Instead, try to reduce dependencies in your OO design. Then pass the objects explicitly to whatever other objects and methods need it. This will not only lead to more elegant, maintainable, and extendable code. It is also a requirement for your code to be testable. Have a look at http://www.youtube.com/watch?v=-FRm3VPhseI for more information on this. |
|||
|
|