您的位置:首页 > 其它

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/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: