Kotlin单例(对象声明)

对象声明就是单例了。object DataProviderManager就可以理解为创建了类DataProviderManager并且实现了单例模式。
测试代码

class test {
    object DataProviderManager {
        fun registerDataProvider(provider: String) {
            // ……
        }

        val allDataProviders: Collection
            get() = listOf("a")

    }

    fun test() {
        DataProviderManager.registerDataProvider("")
    }
}

class MyClass {
    companion object {
          var a: String = ""
        
        fun create(): MyClass = MyClass()
    }

    fun test() {
        MyClass.create()
    }
}

class MyClass1 {

    companion object {

         @JvmStatic
        var a: String = ""

        @JvmStatic
        fun create(): MyClass1 = MyClass1()
    }

    fun test() {
        MyClass1.create()
    }
}

查看kotlin最终生成的java代码
Tools->Kotlin -> Decompile Kotlin to Java
然后点击上面的Decompile按钮,会得到转化后的java文件,如下

// MyClass.java

import kotlin.Metadata;
import kotlin.jvm.internal.DefaultConstructorMarker;
import org.jetbrains.annotations.NotNull;

public final class MyClass {
   public static final MyClass.Companion Companion = new MyClass.Companion((DefaultConstructorMarker)null);

   public final void test() {
      Companion.create();
   }

   public static final class Companion {
     @NotNull
      public final String getA() {
         return MyClass.a;
      }

      public final void setA(@NotNull String var1) {
         Intrinsics.checkParameterIsNotNull(var1, "");
         MyClass.a = var1;
      }

      @NotNull
      public final MyClass create() {
         return new MyClass();
      }

      private Companion() {
      }

      // $FF: synthetic method
      public Companion(DefaultConstructorMarker $constructor_marker) {
         this();
      }
   }
}
// test.java

import java.util.Collection;
import kotlin.Metadata;
import kotlin.collections.CollectionsKt;
import kotlin.jvm.internal.Intrinsics;
import org.jetbrains.annotations.NotNull;

public final class test {
   public final void test() {
      test.DataProviderManager.INSTANCE.registerDataProvider("");
   }

   public static final class DataProviderManager {
      public static final test.DataProviderManager INSTANCE;

      public final void registerDataProvider(@NotNull String provider) {
         Intrinsics.checkParameterIsNotNull(provider, "provider");
      }

      @NotNull
      public final Collection getAllDataProviders() {
         return (Collection)CollectionsKt.listOf("a");
      }

      private DataProviderManager() {
         INSTANCE = (test.DataProviderManager)this;
      }

      static {
         new test.DataProviderManager();
      }
   }
}
// MyClass1.java

import kotlin.Metadata;
import kotlin.jvm.JvmStatic;
import kotlin.jvm.internal.DefaultConstructorMarker;
import org.jetbrains.annotations.NotNull;

public final class MyClass1 {
  @NotNull
   private static String a = "";
   public static final MyClass1.Companion Companion = new MyClass1.Companion((DefaultConstructorMarker)null);

   public final void test() {
      Companion.create();
   }

@NotNull
   public static final String getA() {
      return Companion.getA();
   }

   public static final void setA(@NotNull String var0) {
      Intrinsics.checkParameterIsNotNull(var0, "");
      Companion.setA(var0);
   }

   @JvmStatic
   @NotNull
   public static final MyClass1 create() {
      return Companion.create();
   }

   public static final class Companion {
      @JvmStatic
      @NotNull
      public final MyClass1 create() {
         return new MyClass1();
      }

      private Companion() {
      }

      // $FF: synthetic method
      public Companion(DefaultConstructorMarker $constructor_marker) {
         this();
      }
   }
}

  1. 看生成的test.java,里面的DataProviderManager就是个单例。object DataProviderManager就可以理解为创建了类DataProviderManager并且实现了单例模式。
    调用DataProviderManager.registerDataProvider("")对应的java代码就是DataProviderManager.INSTANCE.registerDataProvider("")

常见调用单例类方法代码DataProviderManager.getInstance().registerDataProvider(""),只是获得instance方式不一样而已

  1. Companion object就不是单例,就把它当做静态变量就好了。加了@JvmStatic之后MyClass1中多了private static String a = "";public static final MyClass1 create() {

在 JVM 平台,如果使用 @JvmStatic 注解,你可以将伴生对象的成员生成为真正的静态方法和字段。

有同学会问,我怎么实现一个单例类给其他类用呢?

就像上面说的一样,object className就相当于定义了一个实现单例模式的类。所以我们在某个kt文件中写如下代码

object UserHelper{
    var username:String = ""
}

class LoginActivity{

    fun doLogin(name:String){
        UserHelper.username = name
    }
}

我们创建了一个UserHelper单例类,用来保存登录用户的信息;LoginActivity里面用户登录,让返回的name赋值给UserHelper
Decompile kotlin to java


public final class LoginActivity {
   public final void doLogin(@NotNull String name) {
      Intrinsics.checkParameterIsNotNull(name, "name");
      UserHelper.INSTANCE.setUsername(name);
   }
}
// UserHelper.java
package com.xstudy.assistteacher.module.inclass;

import kotlin.Metadata;
import kotlin.jvm.internal.Intrinsics;
import org.jetbrains.annotations.NotNull;

public final class UserHelper {
   @NotNull
   private static String username;
   public static final UserHelper INSTANCE;

   @NotNull
   public final String getUsername() {
      return username;
   }

   public final void setUsername(@NotNull String var1) {
      Intrinsics.checkParameterIsNotNull(var1, "");
      username = var1;
   }

   private UserHelper() {
      INSTANCE = (UserHelper)this;
      username = "";
   }

   static {
      new UserHelper();
   }
}

你可能感兴趣的:(Kotlin单例(对象声明))