0 0

Java 单例相关问题5

1.分析下面代码,各自有什么问题

Singleton 模式主要保证在JAVA应用程序中,一个Class只有一个实例存在。一般Singleton模式通常有几种形式:

第一种形式:定义一个类,他的构造函数为private的,它有一个静态的私有变量,在类初始化时实例化,通过一个publicgetIntance方法获取对它的引用,继而调用其中的方法

public class Singleton {

private static Singleton instance = new Singleton();

private Singleton(){}

public static Singleton getInstance() {

return instance;

}

}

第二种形式:

public class Singleton {

private static Singleton instance;

private Singleton() {}

public static Singleton getInstance() {

if(instance == null) {

return new Singleton ();

}

return instance;

}

}

}


问题补充:public class Singleton {
  private static Singleton instance = null;
  public static synchronized Singleton getInstance() {
  if (instance==null)
    instance=new Singleton();
return instance;   }
}
 
2014年9月01日 16:20

5个答案 按时间排序 按投票排序

0 0

还可以再优化:
public class Singleton {
  private static Singleton instance = null;
  public static Singleton getInstance() {
  if (instance !=null )
     return instance ;
  else {

}
 
    instance=new Singleton();
return instance;   }
}


synchronized

2014年9月03日 13:34
0 0

还可以再优化:
public class Singleton {
  private static Singleton instance = null;
  public static Singleton getInstance() {
  if (instance !=null )
     return instance ;
  else {

}
 
    instance=new Singleton();
return instance;   }
}


synchronized

2014年9月03日 13:34
0 0

你看完这篇http://coolshell.cn/articles/265.html
估计就全明白了

2014年9月01日 17:20
0 0

第一种不是懒惰加载,初始化会费时一点点,也许花了时间初始化后面不一定真用得上.

第二种方法如果经常被调用,因为有同步问题,会对性能有影响.


其实单例有更换的办法,可以使用内部类,枚举,或者双重锁.推荐我收藏的几个Blog给你看看.

http://chenjianjx.iteye.com/blog/1839117
http://www.importnew.com/6461.html
http://jiangzhengjun.iteye.com/blog/652440


如果答案对你有帮助,请采纳.

2014年9月01日 16:49
0 0

第一种问题,对象开始可以不初始化,等到获取实例的时候才初始化;
第二种问题,没有线程同步,会有线程安全问题。

2014年9月01日 16:25

相关推荐

Global site tag (gtag.js) - Google Analytics