单例模式的二种正确实现:
方式一:static方式实现(此种方式消除了同步)
class Singleton
{
private Vector v;
private boolean inUse;
private static Singleton instance = new Singleton();
private Singleton()
{
v = new Vector();
inUse = true;
//...
}
public static Singleton getInstance()
{
return instance;
}
}
方式二:synchronized方式(同步方式)
import java.util.*;
class Singleton {
private static Singleton instance;
private Vector v;
private boolean inUse;
private Singleton() {
v = new Vector();
v.addElement(new Object());
inUse = true;
}
public static synchronized Singleton getInstance() {
if (instance == null) // 1
instance = new Singleton(); // 2
return instance; // 3
}
}
上述为单例模式的二种正确实现,大家可能觉得还有其他的实现方式,请参看文章:http://www.ibm.com/developerworks/cn/java/j-dcl.html
转载于:https://www.cnblogs.com/step-by-step1/p/3418174.html
原文链接:https://blog.csdn.net/weixin_30342827/article/details/97732065
本站声明:网站内容来源于网络,如有侵权,请联系我们,我们将及时处理。
还没有人抢沙发呢~