饿汉式:是对象先初始化
class Single
{private static Single s=new Single();
private Single(){};
public static Single getInstance()
{
return s;
}
}
懒汉式:对象是方法被调用时才初始化,也叫做对象的延迟加载。
class Single
{private static Single s=null;
private Single(){};
public static Single getInstance()
{if(s==null)
{synchronized(Single.class)//用双重判断来完成。
{if(s==null)
s=new Single();
}
}
return s;
}
}
|