我正在阅读此处枚举的 Java 教程并有一个问题:http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html#Card
我感到困惑的部分如下:
"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: "
据我所知,将原来的私有(private)“Card”构造函数更改为公共(public)构造函数将使我们能够实例化具有给定花色+等级的“Card”对象的无限数量的副本。所提议的解决方案是创建一个 EnumMap,它将存储四个映射(每个花色对应一个映射),它们本身包含 13 个 Card 对象,并将等级作为它们的键。
现在,如果您想从牌组中检索特定的 Card 对象,只需调用“valueOf”方法即可。我现在的问题是,是什么阻止了您随心所欲地多次调用 valueOf 方法?这不会导致与将原始私有(private)构造函数公开相同的问题吗?
谢谢。
最佳答案
没有。 valueOf()
将始终返回相同的实例。请注意,它实际上是在 static
block 中实例化所有内容。
关于java - 关于单例属性的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2903003/