一、饿汉模式
(1)类加载是线程安全的,静态变量是在类加载的时候进行赋值,所以该模式是线程安全的。
(2)无法懒加载(此处只是伪概念,一般我们使用单例类的时候都需要单例对象。只有当声明了其他的静态方法,在不调用获取单例对象的方法前调用静态方法,才会体现出相对懒汉模式无法懒加载的特性,但实际使用中一般不会在单例类中再声明其他静态方法)
(3)无法给构造函数传参
//Java实现
public class Singleton {
private static Singleton instance=new Singleton();
private Singleton(){}
public static Singleton getInstance(){
return instance;
}
}
//Kotlin实现
object SingletonDemo{}
二、懒汉模式
//Java实现
public class Singleton {
private static Singleton instance;
private Singleton(){}
public static Singleton getInstance(){
if(instance==null){
instance=new Singleton();
}
return instance;
}
}
//kotlin实现
方式一、构造方法无参数
class Singleton private constructor(){
companion object{
val instance: Singleton by lazy { Singleton() }
}
}
方式二、构造方法携带参数
class Singleton private constructor(id: String){
companion object{
private var mInstance: Singleton? = null
fun getInstance(id: String): Singleton{
return mInstance ?: Singleton(id).also { mInstance = it }
}
}
}
三、线程安全懒汉模式
//Java实现
public class Singleton {
private static Singleton instance;
private Singleton(){}
public static synchronized Singleton getInstance(){
if(instance==null){
instance=new Singleton();
}
return instance;
}
}
//kotlin实现
方式一、构造函数无参数
class Singleton private constructor(){
companion object{
private val mInstance: Singleton by lazy { Singleton() }
@Synchronized
fun getInstance(): Singleton{
return mInstance
}
}
}
方式二、构造函数有参数
class Singleton private constructor(id: String){
companion object{
private var mInstance: Singleton? = null
@Synchronized
fun getInstance(id: String): Singleton{
return mInstance ?: Singleton(id).also { mInstance = it }
}
}
}
四、双重校验锁模式
//Java实现
public class Singleton {
private static Singleton instance;
private Singleton(){}
public static Singleton getInstance(){
if(instance==null){
synchronized (Singleton.class){
if(instance==null){
instance=new Singleton();
}
}
}
return instance;
}
}
//kotlin实现
方式一、构造函数无参数
class Singleton private constructor(){
companion object{
val instance: Singleton by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
Singleton() }
}
}
方式二、构造函数有参数
class Singleton private constructor(id: String){
companion object{
private var mInstance: Singleton? = null
fun getInstance(id: String): Singleton{
return mInstance?: synchronized(this){
mInstance?: Singleton(id).also { mInstance = it }
}
}
}
}
五、静态内部类
(1)线程安全
(2)可以懒加载
(3)无法给构造函数传参
//Java实现
public class Singleton {
private static class SingletonHolder{
private static Singleton instance=new Singleton();
}
private Singleton(){
}
public static Singleton getInstance(){
return SingletonHolder.instance;
}
}
//kotlin实现
class Singleton private constructor() {
companion object {
val instance = SingletonHolder.holder
}
private object SingletonHolder {
val holder= Singleton()
}
}
六、java调用kotlin单例
1、object创建的单例
Singleton.INSTANCE.test();
2、companion创建的单例
Singleton.Companion.getInstance().test();