1.饿汉式 : 类加载的时候就创建了
public class HungeryInstance{
private HungeryInstance(){}
//类加载的时候就创建
private static HungeryInstance hgInstance = new HungeryInstance();
public static Hungery getSingleTonInstance(){
return hgInstance;
}
}
2.懒汉式:调用的时候再创建
public class LazyInstance{
private LazyInstance(){}
private static LazyInstance lazyInstance =null;
//为了线程安全,需要加synchronized 关键字确保只会生成单例
public static synchronized getInstance(){
if(lazyInstance==null){
lazyInstance = new LazyInstance();
}
return lazyInstance;
}
}