单例模式写法比较多,记住几个主要的写法。其核心是构造器私有,只有一个实例的单例类
1 恶汉模式
比较简单,可以开始就初始。
- java实现
public class SingleDemo{
private static SingleDemo instance = new SingleDemo();
private SingleDemo(){
}
public static SingleDemo getInstance(){
return instance;
}
}
- kotlin实现
object SingleDemo
举个具体的源码例子
public object Delegate{
public fun<T: Any> notNull():ReadWriteProperty<Any?, T> = NotNullVar()
}
private class NotNullVar<T:Any>():ReadWriteProperty<Any?, T> {
private var value: T? = null
public override getValue(thisRef: Any?, property: KProperty<*>): T{
return value ?: throw IllegalStateException(Property ${property.name} should be initialized before get)
}
public override setValue(thisRef: Any? , prpperty:KProperty<*>,value:T){
this.value = value
}
}
常用第二种写法 双重检测锁
- java实现
这种写法在很多开源项目中都比较常见,看下EventBus的实现
public class EventBus{
private static volatile EventBus defaultInstance;
private EventBus(){
}
public static EventBus getDefault(){
EventBus instance = defaultInstance
if(instance == null){
//synchronized 对象锁保证每次只有一个线程执行初始化对象操作
synchronized(EventBus.class){
instance = EventBus.defaultInstance;
if(instance == null){
instance = new EventBus();
}
}
}
return instance
}
}
- kotlin实现
class EventBus private constructor(){
companion object{
val instance: EventBus by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED ) {
EventBus()
}
}
}
3 常用线程安全不让费内存现方式 静态内部类
- java版
public class EventBus{
private EventBus(){
}
private static class EventBusHolder{
private static EventBus instance = new EventBus()
}
public static EventBus getDefault(){
return EventBusHolder.instance
}
}
- kotlin
class EventBus private constructor(){
companion object{
fun getDefalut(): EventBus{
return EventbusHolder.instance
}
}
private object EventBusHolder{
val instance = EventBus()
}
}