C# Design Patterns – Sharing Info Objects Between Objects

cdesign-patterns

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#.

Best Answer

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

Related Topic