views:

60

answers:

4
+1  Q: 

Sharing objects

Imagine that I have a nice Deck class, in the best OO fashion. It has Cards, which have a Suit and a Rank, it has a Shuffle method, and so on. Now, I'm going to have a lot of concurrent instances of Deck (say this is a casino). The question is: Should there be a different instance of every card across all the decks?

+6  A: 

Card objects would probably be best implemented as immutable objects. In order to create a card, you must pass in a Suit and a Rank, and this Suit and Rank will never be changed at a later time.

From that point of view, since these objects don't change, and since there are a set number to begin with, it makes sense to implement a single static collection containing all 52 possible Card objects, and access these cards from other classes (make the constructor on Card private so that it is impossible to create a card outside of the Card class).

The real distinction here is that Card's themselves don't perform any operations, other operations will act upon cards, so it should be just fine to make a single instance of card.

LorenVS
A: 

It depends on how you're going to use the cards. Probably, though, any extra memory usage from extra instances of Card will be trivial - after all, each card is storing only two bytes of data.

Thom Smith
+4  A: 

It is officially called a Flyweight pattern and was preseneted first in GOFs "Design Patterns". Should be very useful in your case. Since cards never change you may even think to implement them as Enums.

http://en.wikipedia.org/wiki/Flyweight_pattern

eugener
A: 

You ask: "Should there be a different instance of every card across all the decks?" The answer is no: you can use a single instance of each card and share it across all the decks, even if they're running on different threads. The reason is that cards are immutable, so even if two threads call, say, card.getSuit() on the same card, their computations won't interfere.

This is only true, of course, if you write the card class to really be immutable. As soon as you write to some local variable of card, you expose yourself to data races. But I can't think of a reason to do that, so you should be safe.

redtuna