保证一个类仅有一个实例,并提供一个访问它的全局访问点。
核心思路: 有就返回,没有就创建。
1、饿汉
public class Singleton{
private static Singleton = new Singlton();
private Sigleton(){}
private static Singleton getInstance(){
return instance;
}
}
2、懒汉
2.1 普通懒汉 线程不安全
public class Singleton {
private static Singleton instance;
private Singletion(){
}
public static Singletion getInstance(){
if (instance == null){
instance = new Singleton();
}
return instance;
}
}
2.2 线程安全第一版
public class Singleton{
private static Singleton instance;
private Singleton(){}
public static synchronized Singleton(){
if( instance == null){
instance = new Singleton();
}
return instance;
}
}
2.3 DCL 双重校验锁
public class Singleton{
private static volatile Singleton instance;
private Singleton(){}
private static Singleton(){
if( instance == null){
synchronized(Singleton.class){
if( instance == null){
instance = new Singleton();
}
}
}
return instance;
}
}