java时的单例模式
https://juejin.cn/post/6844903590545326088
饿汉式
懒汉式
线程安全的懒汉式
双重校验锁式
静态内部类式
我们参考java单例方式,对应实现kotlin单例方式
饿汉模式
Java实现
public class SingleClass {
private static SingleClass instance=new SingleClass();
private SingleClass(){
}
public static SingleClass getInstance(){
return instance;
}
}
Kotlin实现
object SingleClass
解释
在Kotlin中类没有静态方法。如果要实现java的静态方法并能访问类静态成员的效果,可以把该类声明为一个对象,类似java中的静态成员 【详细了解】。
如上面的类对象实现如下:
public final class SingleClass {
public static final SingleClass INSTANCE;
private SingleClass(){}
static {
SingleClass var0 = new SingleClass();
INSTANCE = var0;
}
}
懒汉模式
Java实现
public class SingleClass {
private static SingleClass instance;
private SingleClass(){}
public static SingleClass getInstance(){
if(instance==null){
instance=new SingleClass();
}
return instance;
}
}
Kotlin实现
class SingleClass private constructor() {
companion object {
private var instance: SingleClass? = null
get() {
if (field == null) {
field = SingleClass()
}
return field
}
fun getSingle(): SingleClass { // 内部已有getInstance方法提供伴生对象用
return instance!!
}
}
}
线程安全的懒汉式
Java实现
public class SingleClass {
private static SingleClass instance;
private SingleClass(){}
public static synchronized SingleClass getInstance(){
if(instance==null){
instance=new SingleClass();
}
return instance;
}
}
Kotlin实现
class SingleClass private constructor() {
companion object {
private var instance: SingleClass? = null
get() {
if (field == null) {
field = SingleClass()
}
return field
}
// kotlin 同步方式
@Synchronized
fun get(): SingleClass{
return instance!!
}
}
}
双重校验锁式
Java实现
public class SingleClass {
private volatile static SingleClass instance;
private SingleClass(){}
public static SingleClass getInstance(){
if(instance==null){
synchronized (SingleClass.class){
if(instance==null){
instance=new SingleClass();
}
}
}
return instance;
}
}
kotlin实现
class SingleClass private constructor() {
companion object {
val instance: SingleClass by lazy {
SingleClass() }
}
}
静态内部类
Java实现
public class SingleClass {
private static class SingleHolder{
private static SingleClass instance=new SingleClass();
}
private SingleClass() {}
public static SingleClass getInstance(){
return SingleHolder.instance;
}
}
kotlin实现
class SingleClass private constructor() {
companion object {
val instance = SingleHolder.holder
}
private object SingleHolder {
val holder= SingleClass()
}
}
网友评论