单例模式:static还是static final?

5

单例模式中,声明实例应该使用 static 还是 static final 更好呢?

请看下面的示例:

static 版本

public class Singleton {

    private static Singleton instance = new Singleton();

    private Singleton() {
    }

    public static Singleton getInstance() {
        return instance;
    }

}

static final version

public class Singleton {

    private static final Singleton INSTANCE = new Singleton();

    private Singleton() {
    }

    public static Singleton getInstance() {
        return INSTANCE;
    }

}

1
点击这里了解实现方法。 - alex2410
3个回答

2
在您特定的情况下,根本没有任何区别。而且您的第二个已经是“实际上最终”的了。
但是,
撇开下面的实现不是线程安全的事实,只是展示与final相关的差异。
在延迟初始化实例的情况下,您可能会感受到差异。请参考延迟初始化。
public class Singleton {

    private static Singleton INSTANCE; /error

    private Singleton() {
    }

    public static Singleton getInstance() {
      if (INSTANCE ==null) {
         INSTANCE = new Singleton(); //error
      }
        return INSTANCE;
    }

}

@alex2410 这只是为了区分最终情况,与线程安全无关。 - Suresh Atta
@alex2410 再次强调,这不是一个解决方案。我在第一行就给出了差异。已经实现的解决方案中没有这种情况。这只是为了展示static finalstatic之间的区别。 - Suresh Atta

0
如果你不想偷懒(并进行“懒初始化”),那么你可能想把它设为final,因为你可以(有意地)这样做:
class Sample {
   static Object o = new Object(); // o is not final. Hence can change.
    static{
     o = new Object();
     o = new Object();
    }
}

我建议使用Enum来实现Singleton,而不是这种方式。

1
我不理解这个解决方案:为什么要这段代码? - ᴜsᴇʀ
1
@user - 这篇文章解释了为什么在OP的当前代码中使用 final 是一个好习惯。 - TheLostMind

-2

人们只使用static来解决延迟初始化的问题。

public class Singleton {

    private static Singleton instance = null;

    private Singleton() {
    }

    public static Singleton getInstance() {
        if (instance == null)
             instance = new Singleton();
        return instance;
    }

}

这样,即使您的应用程序根本不使用它,也无需始终持有一个实例。 只需在应用程序首次需要它时创建即可。


线程安全也取决于对象的其他字段。而且OP的问题是关于是否为最终状态的。 - Codebender

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接