定义: 确保一个类只有一个实例,并提供一个全局访问点。
同步getInstance方法
public class Singleton{
private static synchronized Singleton uniqueInstance;
private Singleton();
public static Singleton getInstance(){
if(uniqueInstance == null){
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
}
使用eagerly create
public class Singleton{
private static Singleton uniqueInstance = new Singleton();
private Singleton();
public static Singleton getInstance(){
return uniqueInstance;
}
}
使用double check
public class Singleton{
private static volatile Singleton uniqueInstance;
private Singleton();
public static Singleton getInstance(){
if(uniqueInstance == null){
synchronized(Singleton.class){
if(uniqueInstance == null){
uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}
}
volatile: