今天从网上看到一个蛮好的Singleton模式的实现方式
下面是经典的实现方式,使用Lazy load方式。
public class Singleton ...{
static Singleton instance;
public static synchronized Singleton getInstance() ...{
if (instance == null)
instance == new Singleton();
return instance;
}
}
synchronized关键字加在getInstance上,也就是说每次调用getInstance都会收到synchronized的影响。
下面是Bob Lee想出来的一种新办法。
public class Singleton ...{
static class SingletonHolder ...{
static Singleton instance = new Singleton();
}
public static Singleton getInstance() ...{
return SingletonHolder.instance;
}
}
这种方式更优雅,并且减少了synchronized的影响。