class SingleDemo2
{
private static Single s = null;
private Single(){}
public static Single getInstance()
{
if(s==null)
s = new Single();
return s;
}
}
class Single
{
private single(){}
private static single s = new Single();
public static Single getInstance()
{
return s;
}
}
第一个是懒汉式:
//在类刚加载进来时,对象的指向为空,没有创建任何对象,当调用getInstance()方法时会进行判断
private static Single s = null;
if(s==null)//如果对象为空
s = new Single();//那么才开始创建对象
return s;//然后将对象返回
第二个是饿汉式:
private static single s = new Single();//当类加载进来之后,就在第一时间创建了对象,并在getInstance()方法中将对象返回
public static Single getInstance()
{
return s;
}
从用户体验的角度来说,我们应该首选饿汉模式。我们愿意等待某个程序花较长的时间初始化,却不喜欢在程序运行时等待太久,给人一种反应迟钝的感觉,所以对于有重量级对象参与的单例模式, 我们推荐使用饿汉模式 。
//懒汉式,当多个线程访问时,不安全,返回的不是同一个对象
class SingleDemo2
{
private static SingleDemo2 s ;
private SingleDemo2(){}//看这里,lz你帖子的写法不对,构造函数与类名名称一致
public static SingleDemo2 getInstance()
{
if(s==null)
s = new SingleDemo2();
return s;
}
}
//饿汉式,线程安全,但是效率比较低
class Single
{
private single(){}
private static single s = new Single();
public static Single getInstance()
{
return s;
}
}
//虽然是安全的,但是效率非常低,一个时候只有一个线程访问,同时返回一个对象
class SingleDemo3
{
private static SingleDemo3 s ; private SingleDemo3(){}
public static synchronized SingleDemo3 getInstance()
{
if(s==null)
s = new Single();
return s;
}
}
//效率高,多线程
class SingleDemo4
{
private static SingleDemo4 s; private SingleDemo4(){}
public static synchronized SingleDemo4 getInstance()
{
if(s==null)
synchornized(SingleDemo4.class)
{
if(s==null)
s = new SingleDemo4();
}
return s;
}
}
哦 好 非常感谢作者: 余磊 时间: 2012-11-20 11:03
我也在这块有缺陷,谢谢各位啦!作者: 杜正冬 时间: 2012-11-20 18:48
饿汉式:先初始化
Single s=new Single();
return s;
懒汉式:判断之后初始化
single s=null;
if(s==null)
s=new Single();
return s;作者: jerry2627 时间: 2012-11-21 02:50
急着创建对象的就是饿汉式呀
class Single
{
private single(){}
private static single s = new Single();
public static Single getInstance()
{
return s;
}
}
吃饱了就懒得动了,总是拖到最后才去创建就是懒汉式额
class SingleDemo2
{
private static Single s = null;
private Single(){}
public static Single getInstance()
{
if(s==null)
s = new Single();
return s;
}
}
个人的区分方式。。。