懒汉模式:
public class SingleLH{
private static SingleLH instance;
private SingleLH() {}
public SingleLH getInstance()
{
if(instance==null)
instance=new SingleLH();
return instance;
}
}
饿汉模式:
public class SingleLH{
private static SingleLH instance=new SingleLH();
private SingleLH() {}
public SingleLH getInstance()
{
return instance;
}
}
懒汉模式可以延迟加载,但是线程不安全,得加锁
饿汉模式线程安全,但是不能延迟加载
so:第三种,静态内部类,既线程安全又可以延迟加载
public class SingleLH{
private SingleLH() {}
private static class Inner{
private static SingleLH instance=new SingleLH();
}
public SingleLH getInstance()
{
return Inner.instance;
}
}