簡體   English   中英

Kotlin對象超類型構造函數

[英]Kotlin Object Supertype Constructor

我需要在Kotlin中實現單例MyClass

要求:

  1. MyClass具有超類型SuperClass ,我需要調用Superclass的構造函數
  2. 我需要將上下文傳遞給MyClass並且需要該上下文來調用Superclass的構造函數。
  3. MyClass是一個單例。

相當於Java:

class MyClass extends SuperClass
{
    // instance variable
    // getInstance() method
    MyClass(Context context)
    {
        super(context);
    }
}

我試圖用一個object解決這個問題,但沒有使它起作用。

有沒有一種方法可以使它與某個對象一起使用,還是必須使用一個companion object

考慮以下超類:

open class MySuperClass(val context: Context) {...}

由於Kotlin對象只有一個空的構造函數,因此您需要一個類似於以下內容的結構:

// Private constructor is only accessible within the class.
class MySingleton private constructor(context: Context) : MySuperClass(context) {
    companion object {
        lateinit var INSTANCE: MySingleton
            // Instance setter is only accessible from within the class.
            private set

        // Custom init function is called from outside and replaces
        // THE WHOLE SINGLETON with a new instance
        // to avoid internal dependencies on the old context.
        fun init(context: Context) {
            INSTANCE = MySingleton(context.applicationContext)
        }
    }

    // Lazily initialized field dependent on a Context instance.
    val prefs by lazy { PreferenceManager.getDefaultSharedPreferences(context) }
}

在使用單例類之前,您需要調用一次init(context) ,而Application是執行此操作的好地方。 每次Instant Run加載新的Application對象時,這還將創建您的單例的新實例,因此您始終會獲得最新的應用程序上下文。

class MyApplication : Application() {
    override fun onCreate() {
        super.onCreate()

        // Eagerly initialized singleton.
        MySingleton.init(this)
    }
}

筆記:

  • Kotlin對象只有一個空的構造函數。 如果需要初始化對象,請使用自定義init函數。
  • 如果您的字段依賴於可能會更改的上下文,則最好使用class而不是object並自己管理當前實例。 如果需要將參數傳遞給單例的超類,則也必須這樣做。
  • 因為您急切地在應用程序的開頭初始化該類(而不是在getInstance(context)的第一次調用時getInstance(context)所以最好將單例對象中的重對象懶惰
  • 如果您的應用程序是多進程的,請找到一種僅在您實際使用它的進程中初始化單例的方法。 (提示:默認情況下,僅在主進程中創建ContentProvider。)

您不需要任何對象或伴隨對象即可實現此目的。 這是在Kotlin中調用超類的構造函數的語法:

class MyClass(context: Context) : SuperClass(context)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM