Question about singleton property
- by Jack
I'm reading the java tutorial for enums located here and have a question: http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html#Card
The part i'm confused about is as follows:
"The Card class, above, contains a
static factory that returns a deck,
but there is no way to get an
individual card from its rank and
suit. Merely exposing the constructor
would destroy the singleton property
(that only a single instance of each
card is allowed to exist). Here is how
to write a static factory that
preserves the singleton property,
using a nested EnumMap: "
Now as I understand, changing the original private "Card" constructor to public would allow us to instantiate an unlimited number of copies of a "Card" object with a given suit+rank. The solution as proposed was to create an EnumMap which would store four Maps (one for each suit), which themselves contained 13 Card objects with the rank as their keys.
And so now if you wanted to retrieve a specific Card object from the deck, you would just call the "valueOf" method. My question now is, what's the prevent you with calling the valueOf method as many times as you like? Wouldn't that lead to the same problem as making the original private constructor public?
Thanks.