2

I'm making a game and I have several cards that are created during the game. Each card needs some info, which is shared between cards of the same type.

So I have a class CardInfo, which holds a name among other things. Now I'm looking for the best way to get the existing CardInfo based on the name, or if none yet exists it is created at that time.


I currently tried two ways, which are quite the same.

First I had a CardInfoManager, which held a list of all known CardInfo, and when asked for one, it checked if it had one, and returned that or created a new one if none existed. I have this as a fully static class, and as a singleton with an Instance method.

I also made an alternative, in which my CardInfoManager (the static version) is basically inside my CardInfo class. So CardInfo had a ByName method, which then checked a static list in CardInfo. This is nice because I can then make the cosntructor private, making sure the info is never created elsewhere.


So I was wondering, what is the best way of doing it? Is there a good pattern for this kind of functionality?

I'm working in c#.

2

To get an object by name, put your objects into a Dictionary.

var dict = new Dictionary<string, CardInfo>();

There are a number of ways to add the CardInfo objects to the dictionary. Here's one:

dict.Add("cardname", new CardInfo { foo = 1, bar = 2 }); 

You retrieve them like this:

var cardInfo = dict.Item("cardname");

or

var cardInfo = dict["cardname"];

Further Reading
Dictionary<TKey, TValue> Class

1

I agree with Robert's suggestion for using Dictionary as a classic lookup for memory based collections.

On the point of the singleton. Use singletons for resource contention ,performance and context If you feel your application might create many instance of cardInfo over and over again and you can manage a singleton safely, then use it. Consider the multiple thread issue when using singletons.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.