在Java中编写单例的不同方法

在Java中编写单例的不同方法

问题描述:

在java中编写单例的经典之处如下:

The classic of writing a singleton in java is like this:

public class SingletonObject
{
    private SingletonObject()
    {
    }

    public static SingletonObject getSingletonObject()
    {
      if (ref == null)
          // it's ok, we can call this constructor
          ref = new SingletonObject();
      return ref;
    }

    private static SingletonObject ref;
}

如果我们需要在多线程情况下运行它们,我们可以添加synchronized关键字。

and we can add synchronized keyword if we need it to run in multithreaded cases.

但我更喜欢把它写成:

public class SingletonObject
{
    private SingletonObject()
    {
        // no code req'd
    }

    public static SingletonObject getSingletonObject()
    {
      return ref;
    }

    private static SingletonObject ref = new SingletonObject();
}

我觉得更简洁,但奇怪的是我没有看到任何样本以这种方式编写的代码,如果我以这种方式编写代码会有什么不良影响吗?

which I think is more concise, but strangely I didn't see any sample code written in this way, is there any bad effects if I wrote my code in this way?

代码之间的区别并且示例代码是在加载类时实例化您的单例,而在示例版本中,直到实际需要它才会实例化。

The difference between your code and the "sample code" is that your singleton is instantiated when the class is loaded, while in the "sample" version, it is not instantiated until it is actually needed.