饿汉式
class Singleton{
private static final Singelton instance = new Singleton();
private Singleton(){}
public static Singleton getInstance(){
return instance;
}
}
懒汉式
class Singleton{
private static Singleton instance = null;
private Singleton(){}
public static getInstance(){
if(instance == null)
return new Singleton();
return instance;
}
}
上诉懒汉式在多线程情况下不安全, 安全写法如下
class Singleton{
private static Singleton instance = null;
private Singleton(){}
public static synchronized getInstance(){
if(instance == null)
return new Singleton();
return instance;
}
}
或者
class Singleton{
private static Singleton instance = null;
private Singleton(){}
public static getInstance(){
synchronized(Singleton.class){
if(instance == null)
return new Singleton();
}
return instance;
}
}