kotlin object

三种语义

  • 匿名内部类
  • 单例模式
  • 伴生对象

定义一个类的同时还创建了对象。

匿名内部类

image.setOnClickListener(object:View.OnClickListener
{

override fun onClick(v:View?){
  gotoPreview()
}
})
  • 函数式(SAM)接口
    https://www.kotlincn.net/docs/reference/fun-interfaces.html
image.setOnClickListener {
       gotoPreview()
}

单例模式

object UserManager{
  fun login(){
  }
}
  • 编译器实现
public final class UserManager{
public static final UserManager INSTANCE;
static{//虚拟机保证它只会被执行一次
UserManager var0 = new UserManager();
INSTANCE = var0;
}

private UserManager(){
}

public void login(){
}

}
  • 懒加载
object UserManager{
val user by lazy { loadUser() }

private fun loadUser():User{
  return User.create("tom")
}
 fun login(){
}

}
  • Double Check
class UserManager private constructor(name:String){
  compaion object {
    @Volatile private var INSTANCE : UserManager? = null;
  
    fun getInstance(name:String):UserManager{
      INSTANCE?:synchronized(this){
      INSTANCE?:UserManager(name).alse{INSTANCE = it}
    }
    }
}
}

UserManager.getInstance("Tom")
  • 抽象类模板
abstract class BaseSington {
@Volatile 
private var instance :T? = null

protect abstract fun creator(param:P):T{

}  

fun getInstance(param:P):T= instance ?:synchronized(this){
instance?:creator(param).alse{ instance = it}
}
}

  • 构造传参

伴生对象

1、没有java static关键字
2、定义静态方法和静态变量

class Test{
object InnerPerson{
  fun foo(){
  }
}
}

Test.InnerPerson.foo()

编译后

public final class Test {
   @Metadata(
      mv = {1, 4, 3},
      bv = {1, 0, 3},
      k = 1,
      d1 = {"\u0000\u0012\n\u0002\u0018\u0002\n\u0002\u0010\u0000\n\u0002\b\u0002\n\u0002\u0010\u0002\n\u0000\bÆ\u0002\u0018\u00002\u00020\u0001B\u0007\b\u0002¢\u0006\u0002\u0010\u0002J\u0006\u0010\u0003\u001a\u00020\u0004¨\u0006\u0005"},
      d2 = {"Lcom/jh/menu/Test$InnerPerson;", "", "()V", "foo", "", "format.PublicComponent"}
   )
   public static final class InnerPerson {
      @NotNull
      public static final Test.InnerPerson INSTANCE;

      public final void foo() {
      }

      private InnerPerson() {
      }

      static {
         Test.InnerPerson var0 = new Test.InnerPerson();
         INSTANCE = var0;
      }
   }
}

实际上是通过调用单例InnerPerson的实例上的方法

  • 实现类似Java静态方法的代码

你可能感兴趣的:(kotlin object)