1、饿汉式实现
//Java实现
public class SingletonDemo {
private static SingletonDemo instance=new SingletonDemo();
private SingletonDemo(){
}
public static SingletonDemo getInstance(){
return instance;
}
}
//Kotlin实现
object SingletonDemo {
fun test(){
println("SingletonDemo")
}
}
//调用
SingletonDemo.test()
object 关键字能够一行带代码实现单利
查看Kotlin对应字节码
Android Studio(选择Tools工具栏,选择"Kotlin",选择“Show Kotlin Bytecode"
点击"Decompile" 根据字节码得到以下代码
public final class SingletonDemo {
public static final SingletonDemo INSTANCE;
public final void test() {
String var1 = "SingletonDemo";
System.out.println(var1);
}
static {
SingletonDemo var0 = new SingletonDemo();
INSTANCE = var0;
}
}
1、懒汉式实现
//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!!
//"!!"加在变量名后,如果对象为null,那么系统一定会报异常!
}
}
}
主构造函数私有化
companion object~伴生对象,每个类都可以实现一个伴生对象,它是该类的所有实例共有的对象。它将类似于Java中的静态字段;
网友评论