单例模式的二种正确实现:
方式一: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