单例模式是应用中比较常用到的模式之一,本文主要讲单例模式的实现方式
1.懒汉实现方式
public class Singleton{
private Singleton(){};
private static Singleton instance;
public static synchronized Singleton getInstance(){
if(instance==null){
instance= new Singleton();
}
return instance;
}
}
2.Double Check Lock(DCL)实现单例
public class Singleton{
private Singleton(){};
private static Singleton instance;
public static Singleton getInstance(){
if(instance==null){
synchronized(Singleton.class){
if(instance==null){
instance= new Singleton();
}
}
}
return instance;
}
}
3.静态内部类单例模式
public class Singleton{
private Singleton(){};
private static Singleton instance;
public static Singleton getInstance(){
return SingletonHolder.instance;
}
private static class SingletonHolder{
private static final Singleton instance = new Singleton();
}
}