enum 是实现单例最好的解决方案吗

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/
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值