代码
代码语言:txt复制// 单例关键字object,声明为单例类之后会立即在内存中创建单例对象,并一直存在。
object BigHeadSon:IWashBow {
override fun washBow() {
println("洗碗赚100000000元钱")
}
}
fun main(args: Array<String>) {
BigHeadSon.washBow()
}
饿汉式
代码语言:txt复制// Java实现
public class SingletonDemo {
private static SingletonDemo instance = new SingletonDemo();
private SingletonDemo(){
}
public static SingletonDemo getInstance(){
return instance;
}
}
// Kotlin实现
object SingletonDemo
懒汉式
代码语言:txt复制// Java实现
public class SingletonDemo {
private static SingletonDemo instance;
private SingletonDemo(){}
public static SingletonDemo getInstance(){
if(instance == null){
instance = new SingletonDemo();
}
return instance;
}
}
// Kotlin实现
class SingletonDemo private constructor() {
companion object {
private var instance: SingletonDemo? = null
get() {
if (field == null) {
field = SingletonDemo()
}
return field
}
fun get() : SingletonDemo {
// 细心的小伙伴肯定发现了,这里不用getInstance作为为方法名,是因为在伴生对象声明时,内部已有getInstance方法,所以只能取其他名字
return instance!!
}
}
}
其他
Https://www.jianshu.com/p/5797b3d0ebd0