单身形态 [英] Singleton pattern
本文介绍了单身形态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下代码片段很简单,
public MyClass getInstance() {
if(uniqueInstance == null) {
uniqueInstance = new MyClass();
}
return uniqueInstance;
}
以下是做什么?
public MyClass getInstance() {
if(uniqueInstance == null) {
synchronized(MyClass.class) {
uniqueInstance = new MyClass();
}
}
return uniqueInstance;
}
推荐答案
它可以安全地阻止由至少两个线程引起的竞争条件,这两个线程同时进入,如果
阻止。
It's a poor attempt to make it threadsafe to prevent a race condition caused by at least two threads which have simultaneously entered the if
block.
更安全的方法是添加一个额外的空值,也称为双重锁定。
A bit more safe approach is adding an extra nullcheck, also known as double-checked locking.
public MyClass getInstance() {
if (uniqueInstance == null) {
synchronized(MyClass.class) {
if (uniqueInstance == null) {
uniqueInstance = new MyClass();
}
}
}
return uniqueInstance;
}
然而,我通常更喜欢 只需在Singleton上创建一个模式。
However, I usually prefer Just Create One pattern over Singleton.
这篇关于单身形态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文