案例模式分为懒汉式和饿汉式
/**
*
* 单利模式有两种,
* 懒汉式:延迟加载,多线程有问题。加同步锁,消耗资源,需要双重否定判断。锁为类级别的
* 饿汉式:每次都需要创建
* @author hous
*
*/
public class Singleton {
// 饿汉式
// public static final Singleton instance = new Singleton();
// private Singleton(){}
// public static Singleton getInstance()
// {
// return instance;
// }
// 懒汉式加锁效率比较低
private static Singleton instance = null;
private Singleton(){}
public static Singleton getInstance()
{
if(instance == null)
{
synchronized(Singleton.class)//多线程同步
{
if(instance == null)
{
instance = new Singleton();
}
}
}
return instance;
}
}