确保一个类只有一个实例,并提供全局访问点。
- 饿汉式
线程安全 非延时初始化
// Java 饿汉式
public class SingletonJava {
private SingletonJava() {
}
private static SingletonJava instance = new SingletonJava();
public static SingletonJava getInstance() {
return instance;
}
}
// Kotlin 饿汉式
object SingletonKotlin
- 懒汉式
线程不安全 延时初始化
// Java 懒汉式
public class SingletonJava {
private SingletonJava() {
}
private static SingletonJava instance;
public static SingletonJava getInstance() {
if (instance == null) {
instance = new SingletonJava();
}
return instance;
}
}
// Kotlin 懒汉式
class SingletonKotlin private constructor() {
companion object {
private val instance: SingletonKotlin? = null
get() = field ?: SingletonKotlin()
// 此处方法名不能使用getInstance,因为kotlin在伴生对象声明时已有getInstance方法,会冲突
fun get(): SingletonKotlin {
return requireNotNull(instance)
}
}
}
- 线程安全的懒汉式
线程安全 延时初始化
// Java 线程安全的懒汉式
public class SingletonJava {
private SingletonJava() {
}
private static SingletonJava instance;
public static synchronized SingletonJava getInstance() {
if (instance == null) {
instance = new SingletonJava();
}
return instance;
}
}
// Kotlin 线程安全的懒汉式
class SingletonKotlin private constructor() {
companion object {
private val instance: SingletonKotlin? = null
get() = field ?: SingletonKotlin()
// 此处方法名不能使用getInstance,因为kotlin在伴生对象声明时已有getInstance方法,会冲突
@Synchronized
fun get(): SingletonKotlin {
return requireNotNull(instance)
}
}
}
- 双重校验锁
线程安全 延时初始化
// Java 双重校验锁
public class SingletonJava {
private SingletonJava() {
}
private volatile static SingletonJava instance;
public static SingletonJava getInstance() {
if (instance == null) {
synchronized (SingletonJava.class) {
if (instance == null) {
instance = new SingletonJava();
}
}
}
return instance;
}
}
// Kotlin 双重校验锁
// Kotlin中有个天然特性可以支持线程安全DCL的单例 Companion Object + lazy属性代理
class SingletonKotlin private constructor() {
companion object {
val instance: SingletonKotlin by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
SingletonKotlin()
}
}
}
- 静态内部类
线程安全 延时初始化
// Java 静态内部类
public class SingletonJava {
private SingletonJava() {
}
private static class SingletonHolder {
private static SingletonJava instance = new SingletonJava();
}
public static SingletonJava getInstance() {
return SingletonHolder.instance;
}
}
// Kotlin 静态内部类
class SingletonKotlin private constructor() {
private object SingletonHolder {
val holder = SingletonKotlin()
}
companion object {
val instance = SingletonHolder.holder
}
}
- 枚举
线程安全 非延时初始化
// Java 枚举
public enum SingletonJava {
INSTANCE
}
// Kotlin 枚举
enum class SingletonKotlin {
INSTANCE
}
枚举实现单例,可防止反序列化,若使用其他方式,则需添加readResolve方法,并返回instance即可