Global-like data in C#

Started by
2 comments, last by gharen2 16 years, 10 months ago
I am working on a game where there is some information that is constantly used by many portions of the program. For instance, the map data and the unit template data are used in many places other than just when displaying the map or populating the unit to build dialog. The map boundaries, for example, are used by the AI routines when enumerating the hexes that a given city manager is responsible for. I've been passing the needed data into the routines, but then I came across the singleton pattern, so I started looking into other ways of doing this. Then I learned the singleton pattern was evil :-) so I came here to get some advice. What are some methods of doing this. Should I just keep passing the data in as parameters? Thanks in advance.
Advertisement
Hmm... well, you can have a "Game State" object, for example. This object would hold the other objects that constitute the Map etc...

Then in the main routine, initialize an instance of the Game State object. Essentially it's probably similar to the singleton notion, but sometimes when you need data you need data.

From there, you could do a few things. You could pass any other objects that need to know about the Game State a reference to said object. You could also set up an Observer/Observable pattern where objects that just need to know when the game state changes are informed when changes occur.

Hopefully that helps... personally though, I say do what you understand. Sometimes following the rules of OO Programming can lead to solutions that, while much easier to maintain, are less efficient: and if it's a private project, you may not have to worry as much about said maintenance.
- Edgar Verona"But when a long train of abuses and usurpations, pursuing invariably the same Object evinces a design to reduce them under absolute Despotism, it is their right, it is their duty, to throw off such Government, and to provide new Guards for their future security."
I don't know if it would be a problem, but the gamestate would be huge, containing the map and some even more elaborate data.

I don't actually find passing the parameters to be inelegant, but I worry about overhead. Since I'm not actually using the data passed for more than lookups and such in most cases, can I pass by reference and then stop worrying about the memory usage and such?
When dealing with reference types, there's no more overhead to passing around a large object than a small one. This is because you're passing around the reference to it, not the object itself. A reference to a big object is the same size as a reference to a small one.

So make sure it's a class, and not a struct, and pass it to the constructors of any class that uses it.

This topic is closed to new replies.

Advertisement