开发者

Question about singleton property

开发者 https://www.devze.com 2023-01-01 11:04 出处:网络
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

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 w开发者_JAVA技巧rite 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.


No. valueOf() will always return the same instance. Notice, it is actually instantiating everything once in a static block.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号