关于单例属性的问题
我正在阅读位于此处的枚举的 java 教程,并有一个问题: http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html#Card
我感到困惑的部分如下:
“上面的 Card 类包含一个 返回牌组的静态工厂, 但没有办法得到 个人卡牌的等级和 套装。仅仅暴露构造函数 会破坏单身财产 (每个只有一个实例 卡是允许存在的)。这是如何 编写一个静态工厂 保留单例属性, 使用嵌套的 EnumMap:“
现在据我了解,将原始的私有“Card”构造函数更改为公共将允许我们实例化具有给定花色+等级的“Card”对象的无限数量的副本。建议的解决方案是创建一个 EnumMap 来存储 4 个 Map(每种花色一个),它们本身包含 13 个 Card 对象,并以等级作为键,
因此现在如果您想从牌组中检索特定的 Card 对象,您只需调用“ valueOf”方法。我现在的问题是,什么会阻止您多次调用 valueOf 方法?这不会导致与将原始私有构造函数公开相同的问题吗?
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不会。
valueOf()
将始终返回相同的实例。请注意,它实际上是在static
块中实例化所有内容。No.
valueOf()
will always return the same instance. Notice, it is actually instantiating everything once in astatic
block.