1.懒汉模式:线程不安全
public class Singleton{
private static Singleton instance;
private Singleton(){}
public static Singleton getInstance(){
if(instance==null){
instance =new Singleton();
}
return instance;
}
}
2.懒汉模式,线程安全的
public class Singleton{
pirvate static Singleton instance;
private Singleton(){}
public static synchronized Singleton getInstance(){
if(instance==null)
instance=new Singleton();
}
return instance;
}
3.饿汉式:类加载时就初始化,浪费内存
public class Singleton{
private static Singleton instance =new Singleton();
private Singleton(){}
public static Singleton getInstance(){
return instance;
}
}