一、单例模式
1、第一种形式 : 饿汉式单例
public class Singleton {
private static Singleton instance = new SingleTon();
public Singleton() {}
public static sychronized Singleton getInstance() {
instance = new Singleton()
}
}
“饿汉式”是不管你用不用的上,一开始就建立这个单例对象,线程不安全
2、第二种形式 : 懒汉式单例
public class Singleton {
private static Singleton instance = null ;
private Singleton() { }
public static synchronized Singleton getInstance() {
if( instance == null )
instance = new Singleton();
return instancel
}
}
懒汉式是在你真正用到的时候才去建立单例对象,线程安全
二、spring boot 默认单例模式
