- 定义:单例模式确保一个类只有一个实例,并提供一个全局访问点。
- 懒汉模式:
/**
* 懒汉
*/
public class LazySingleton {
private static LazySingleton lazySingleton;
private LazySingleton() {
}
public static LazySingleton getInstance() {
if (lazySingleton == null) {
lazySingleton = new LazySingleton();
}
return lazySingleton;
}
}
- 饿汉模式
/**
* 饿汉1
*/
public class HungrySingleton {
private static HungrySingleton hungrySingleton = new HungrySingleton();
private HungrySingleton() {
}
public static HungrySingleton getInstance() {
return hungrySingleton;
}
}
- 伪饿汉模式
/**
* 饿汉2
*/
public class HungrySingleton2 {
private volatile static HungrySingleton2 hungrySingleton2;
private HungrySingleton2() {
}
public static HungrySingleton2 getInstance() {
if (hungrySingleton2 == null) {
synchronized (HungrySingleton2.class) {
if (hungrySingleton2 == null) {
hungrySingleton2 = new HungrySingleton2();
}
}
}
return hungrySingleton2;
}
}