在Java中编写单例的不同方法 [英] Different ways to write singleton in Java

查看:86
本文介绍了在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.

这篇关于在Java中编写单例的不同方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆