Single类一进内存,就已经创建好了对象。
class Single
{
private static Single s = new Single();
private Single(){}
public static Single getInstance()
{
return s;
}
}
*/
//对象是方法被调用时,才初始化,也叫做对象的延时加载。成为:懒汉式。
//Single类进内存,对象还没有存在,只有调用了getInstance方法时,才建立对象。
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;
}
}
class
{
public static void main(String[] args)
{
System.out.println("Hello World!");
}
}
懒汉式存在安全隐患,需要使用同步来解决,效率不够高。
定义单例,建议使用饿汉式。
作者: 李会启 时间: 2012-2-29 12:19
饿汉式:
public class Singleton{
private static Singleton singleton = new Singleton ();
private Singleton (){}
public Singleton getInstance(){return singletion;}
}
懒汉式:
public class Singleton{
private static Singleton singleton = null;
public static synchronized synchronized getInstance(){
if(singleton==null){
singleton = new Singleton();
}
return singleton;
}
}
class Single
{
private static final Single s=new Single();
private Sinlge(){}
public static void getinstance()
{
return s;
}
}
*/
懒汉式 特点:使用对象才初始化, 叫做对象的延迟加载
class Single
{
private static Single s=null;
private Single(){}
public static void getInstance()
{
if(s==null)
synchronized(Single.class)//锁:该类所属的字节码文件
{
if(s==null)
{
Single s=new Single