Question about singleton property

Posted by Jack on Stack Overflow See other posts from Stack Overflow or by Jack
Published on 2010-05-25T08:12:44Z Indexed on 2010/05/25 8:21 UTC
Read the original article Hit count: 182

Filed under:

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.

© Stack Overflow or respective owner

Related posts about java