自 Java 5 以来最好的单例模式
从 Java 5 开始,据说创建单例的最佳方法是使用单元素枚举类型。
示例:
public enum SuperSingleton implements Zooma{
INSTANCE;
/**
*/
public void fightTheBattle(){
System.out.println("I am fighting the battle!!!");
}
@Override
public void runningWild() {
//This is method implemented from the Zooma interface.
}
}
根据 Joshua Bloch 的说法,单元素枚举类型单例是;
- 更简洁
- 免费提供序列化机制
- ,并提供针对多重实例化的铁证。
我可以看到它如何更加简洁以及它如何提供针对多重实例化的铁定, 但是它如何免费提供序列化机制?
它是单例通过成为枚举而获得的东西吗?
Since Java 5 it is said that the best way to create a singleton is by a single-element enum type.
Example:
public enum SuperSingleton implements Zooma{
INSTANCE;
/**
*/
public void fightTheBattle(){
System.out.println("I am fighting the battle!!!");
}
@Override
public void runningWild() {
//This is method implemented from the Zooma interface.
}
}
According to Joshua Bloch, the single-element enum type singleton is;
- more concise
- provides the serialization machinery for free
- and provides an ironclad against multiple instantiation.
I can see how it is more concise and how it provides an ironclad against multiple instantiation,
but how does it provide the serialization machinery for free?
Is it something the singleton gets by being an enum?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,枚举都是从
Enum 扩展而来的
类,它实现了Serialized
。Yes, Enums are all extended off of the
Enum
class, which implementsSerializable
.我不是 100% 确定,但我认为如果您反序列化一个序列化的单例次数超过一次,您最终可能会得到多个实例。枚举实例将始终保持单例。
因此,与仅实现序列化相比,您可以获得“更多的序列化”。
I'm not 100% sure, but I think if you deserialize a serialized singleton more then once you might end up with more than one instance. An enum instance will always stay a singleton.
So you get 'more serialization' then what you get from just implementing serialization.
http://download.oracle.com/javase /1.5.0/docs/api/java/lang/Enum.html
是的:)
http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Enum.html
yes :)