【发布时间】:2018-10-08 13:19:49
【问题描述】:
我看到网上有一个Singleton的教程,为了实现多线程并确保实例只被实例化一次。本教程下面有代码,但在代码中,则有重复代码,因为他们要确保实例不为空。
if(instance == null){}
但是,这个条件检查出现了两次,这是重复吗?
public class Singleton {
private static Singleton instance;
private Singleton(){
//Here runs a lot code, that's why we don't want to instantiate here
}
// Using synchronized to ensure Singleton (only instantiate once) when
//implement multi threading.
public static Singleton getInstance(){
if(instance == null){
synchronized(Singleton.class){
if(instance == null){
instance = new Singleton();
}
}
}
return instance;
}
}
【问题讨论】:
-
它被称为double checked locking 是有原因的。
-
为确保没有多线程破坏单例模式,请在您的类中添加
object并在检查 null 之前添加lock -
@nalka OP 没有询问对象锁定。他们在问为什么
instance会被检查两次。请不要添加无关信息,因为它只会混淆OP。 -
事实检查了两次,但在这种特定情况下,有充分的理由检查两次。检查@bommelding 链接(它是java,但概念相同)或我的答案,我试图解释为什么需要第二个
if。
标签: c# design-patterns singleton code-duplication code-cleanup