實現(xiàn)單例模式的5種方式:
1.餓漢式單例(立即加載方式)
public class Singleton{
private Singleton(){};
private static Singleton single = new Singleton();
public static Singleton getInstance(){
return single;
}
}
2.懶漢式單例(延遲加載方式)
public class Singleton{
private Singleton(){};
private static Singleton single =null ;
public static Singleton getInstance(){
if(Singleton == null){
Singleton = new Singleton();
}
return Singleton ;
}
}
多線程環(huán)境下使用syhchronized
public class Singleton{
private Singleton(){};
private static Singleton single =null ;
public static Singleton getInstance(){
// 等同于 synchronized public static Singleton getInstance()
syhchronized(Singleton.class){
if(Singleton == null){
Singleton = new Singleton();
}
}
return Singleton ;
}
}
利用雙重檢查提高效率
public class Singleton{
private Singleton(){};
private static Singleton single =null ;
public static Singleton getInstance(){
if(Singleton == null){
syhchronized(Singleton.class){
if(Singleton == null){
Singleton = new Singleton();
}
}
}
return Singleton ;
}
}
3.靜態(tài)內(nèi)部類實現(xiàn)
public class Singleton{
private Singleton(){};
private static class InnerClass {
private static Singleton single =new Singleton();
}
public static Singleton getInstance(){
return InnerClass .single;
}
}
4.靜態(tài)代碼塊
public class Singleton{
private Singleton(){};
private static Singleton single =null ;
static {
single = new Singleton();
}
public static Singleton getInstance(){
return single;
}
}
5.內(nèi)部枚舉類實現(xiàn)
public class SingletonFactory {
// 內(nèi)部枚舉類
private enum EnmuSingleton{
Singleton;
private Singleton singleton;
//枚舉類的構(gòu)造方法在類加載是被實例化
private EnmuSingleton(){
singleton = new Singleton();
}
public Singleton getInstance(){
return singleton;
}
}
public static Singleton getInstance() {
return EnmuSingleton.Singleton.getInstance();
}
}
class Singleton{
public Singleton(){}
}