关于单例属性的问题

发布于 2024-09-03 12:10:35 字数 668 浏览 1 评论 0原文

我正在阅读位于此处的枚举的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

沦落红尘 2024-09-10 12:10:35

不会。valueOf() 将始终返回相同的实例。请注意,它实际上是在 static 块中实例化所有内容。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文