单例模式思想:保证一个类仅有一个实例,并提供一个访问它的全局访问点。
主要解决问题:一个全局使用的类频繁地创建与销毁。
//懒加载 线程不安全
class Singleton1 {
private Singleton1() {}
private static Singleton1 singleton;
public static Singleton1 getInstance() {
if(singleton == null) {
singleton = new Singleton1();
}
return singleton;
}
}
//懒加载 线程安全 效率低
class Singleton2 {
private Singleton2() {}
private static Singleton2 singleton;
public static synchronized Singleton2 getInstance() {
if(singleton == null) {
singleton = new Singleton2();
}
return singleton;
}
}
//非懒加载 线程安全 效率高 浪费内存
class Singleton3 {
private Singleton3() {}
private static Singleton3 singleton = new Singleton3();
public static Singleton3 getInstance() {
return singleton;
}
}
//懒加载 线程安全 效率高
class Singleton4 {
private Singleton4() {}
private static Singleton4 singleton;
public static Singleton4 getInstance() {
if(singleton == null) {
synchronized(Singleton4.class) {
if(singleton == null) {//如果只有一层if校验,相当于所有线程排队创建新的实例对象
singleton = new Singleton4();
}
}
}
return singleton;
}
}