今天学了一下java中的单例模式。
最简单、成熟的单例模式是这么设计的:
public class Singleton {
public final static Singleton INSTANCE = new Singleton();
private Singleton() {
// Exists only to defeat instantiation.
}
}
这里使用pubic final static限定词使得INSTANCE在声明时(?是否等同于编译时?) 就被实例化,使用起来是这样的:
Singleton singleton = Singleton.INSTANCE;
singleton.dothis();
singleton.dothat();
...
该方案的缺点是没有办法改变它,以便后来你可能想要允许多个单例类的实例。而且没有办法传入参数动态地生成实例。
另外一种简单成熟的方式是使用同步:
public synchronized static Singleton getInstance() {
if(singleton == null) {
singleton = new Singleton();
}
return singleton;
}
这种方法的缺点是有同步的开销。
见网上有解决这以上两种设计的矛盾的方法:
private static int hasInitialized=0;
private static Singleton INSTANCE;
public static Singleton getInstance(){
if(hasInitialized==0){
synchronized(Singelton.class){
//Double checking
if(hasInitialized==0){
INSTANCE=new Singleton();
hasInitialized=1;
}
}
}
}
不确定这种方法可不可行。
以上只是今天学习的总结。具体参考 http://calmness.iteye.com/blog/60179 和 http://www.iteye.com/topic/211471