enum 是实现单例最好的解决方案吗
2016-01-17 16:21
295 查看
enum 是实现单例最好的解决方案吗
你一定听说过很多次,enum总是实现单例模式最好的选择。那enum是最好的选择吗?比起其它实现方式有什么好的地方?我们看一下。要实现一个单例模式是很棘手的,我也在另一篇博客上提到了好几个实现方法,见http://howtodoinjava.com/2012/10/22/singleton-design-pattern-in-java/。博客中清楚的指出,enums 对单例模式的实现保证了实例的唯一性和线程的安全性。而且也是实现单例模式很好的方方式。
Problems with enum as singleton
Having said that, like with any other thing in universe, this approach does have it’s disadvantages which you will need to consider before making any decision.
enums do not support lazy loading.
Though it’s very very rare but if you changed your mind and now want to convert your singleton to multi-ton, enum would not allow this.
If above both cases are no problem for anybody, the enum is probably best choice.
Anyways, on side note, after compilation java enums are converted to classes only with additional methods e.g. values() and valueOf()… etc.
enum based singleton example
Once you have decided to write enum based singleton, writing it is really easy e.g.
enum Singleton { INSTANCE; // instance vars, constructor private final Connection connection; Singleton() { // Initialize the connection connection = DB.getConnection(); } // Static getter public static Singleton getInstance() { return INSTANCE; } public Connection getConnection() { return connection; } }
Now you use can use final Singleton s = Singleton.getInstance(). Remember that since this is an enum you can always access this via Singleton.INSTANCE as well.
Happy Learning !!
http://howtodoinjava.com/2015/10/20/is-enum-really-best-for-singletons/
相关文章推荐
- android事件分发机制
- (一)计算机网络概述
- 单调栈的运用
- 注释文档 -Java
- 图像中的灰度共生矩阵
- 2016 系统设计第一期 (档案一)MVC 和 Bootstrap 表单转换
- 蓝懿IOS/阶段性总结
- Java学习----finally块
- C#与C++区别(转)
- Netfilter中conntrack的建立过程
- 为按钮设置监听的四种方法
- Caffe安装笔记
- 执行make出现“Warning: File `xxx.c' has modification time 2.6e+04 s in the future“警告的解决方法
- PHP正则表达式 解析优酷视频ID
- Hadoop Yarn connection refused 警告
- Index Reorganize 和 Rebuild 的区别
- 夺命雷公狗---微信开发03----接收订阅事件推送
- 作业调度算法
- [codevs1159]最大全0子矩阵
- CSS 水平居中设置