2015-09-03 67 views
4

最好将单例的实例声明为staticstatic final单例模式:静态还是静态最终?

请看下面的例子:

static版本

public class Singleton { 

    private static Singleton instance = new Singleton(); 

    private Singleton() { 
    } 

    public static Singleton getInstance() { 
     return instance; 
    } 

} 

static final版本

public class Singleton { 

    private static final Singleton INSTANCE = new Singleton(); 

    private Singleton() { 
    } 

    public static Singleton getInstance() { 
     return INSTANCE; 
    } 

} 
+1

阅读[这里](http://stackoverflow.com/questions/70689/what-is-an-efficient-way-to-implement-a-singleton-pattern-in-java)关于实现。 – alex2410

回答

-2

人们只使用static延迟初始化

public class Singleton { 

    private static Singleton instance = null; 

    private Singleton() { 
    } 

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

} 

这样,即使您的应用程序根本没有使用它,也不需要始终保存一个实例。 仅在应用程序需要它时才创建它。

+3

非线程安全实现 – alex2410

+0

线程安全还取决于对象的其他字段。而OP的问题是关于是否是最终的... – Codebender

2

在你的特殊情况下,没有任何区别。而你的第二个已经effectively final

保持抛开事实之下实现不是线程安全的,只是表示对于最终的差别。

如果您的实例延迟初始化,您可能会感觉不同。看起来懒惰的初始化。

public class Singleton { 

    private static Singleton INSTANCE; /error 

    private Singleton() { 
    } 

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

} 
+1

非线程安全执行 – alex2410

+0

@ alex2410这仅仅是为了在最终的情况下的差异。不是线程安全的问题。 –

+0

它只是基于错误的解决方案 – alex2410

0

如果你不想偷懒(做延迟初始化),那么你可能要使它final,因为你可能(有意)做这样的事情:

class Sample { 
    static Object o = new Object(); // o is not final. Hence can change. 
    static{ 
    o = new Object(); 
    o = new Object(); 
    } 
} 

我会建议Singleton使用Enum而不是这个。

+1

我不明白这个解决方案:为什么这段代码? –

+1

@user - 这个解释了为什么在OP的当前代码中使用'final' – TheLostMind