您的位置:程序门 -> java -> j2ee / ejb / jms



我们来说说:懒汉式和饿汉式的区别


[收藏此页] [打印本页]选择字色:背景色:字体:[][][]


我们来说说:懒汉式和饿汉式的区别
发表于:2007-07-10 23:05:44 楼主
在创建类的对象时,单例模式下的懒汉式和饿汉式具体说有什么区别?
用适当的例子说明就更好啊!!!
发表于:2007-07-14 14:40:141楼 得分:0
//   懒汉:
public   class   singleton   {
private   static   singleton   obj   =   null;

private   singleton()   {
//   todo   auto-generated   constructor   stub
}

public   synchronized   static   singleton   getinstance()   {
if   (obj   ==   null)
obj   =   new   singleton();
return   obj;
}
}

//   饿汉:
public   class   singleton   {
private   static   singleton   obj   =   new   singleton();

/**
  *  
  */
private   singleton()   {
//   todo   auto-generated   constructor   stub
}

public   static   singleton   getinstance()   {
    return   obj;
}
}
发表于:2007-07-15 22:29:132楼 得分:0
懒汉式是在第一次调用静态方法的时候才初始化实例。饿汉式是在类加载到内存时就初始化实例了。
发表于:2007-07-16 10:53:333楼 得分:0
up


快速检索

最新资讯
热门点击