委托可以用作减少样板的图层

考虑 Kotlin 的 Null Type 系统和 WeakReference<T>

所以,假设我们必须保存某种引用,我们希望避免内存泄漏,这里是 WeakReference 的用武之地。

以此为例:

class MyMemoryExpensiveClass {
    companion object {
        var reference: WeakReference<MyMemoryExpensiveClass>? = null

        fun doWithReference(block: (MyMemoryExpensiveClass) -> Unit) {
            reference?.let {
                it.get()?.let(block)
            }
        }
    }

    init {
        reference = WeakReference(this)
    }
}

现在这只是一个 WeakReference。要减少此样板,我们可以使用自定义属性委托来帮助我们:

class WeakReferenceDelegate<T>(initialValue: T? = null) : ReadWriteProperty<Any, T?> {
    var reference = WeakReference(initialValue)
        private set
    
    override fun getValue(thisRef: Any, property: KProperty<*>): T? = reference.get()
    
    override fun setValue(thisRef: Any, property: KProperty<*>, value: T?) {
        reference = WeakReference(value)
    }
}

所以现在我们可以像普通的可空变量一样使用 WeakReference 包装的变量!

class MyMemoryExpensiveClass {
    companion object {
        var reference: MyMemoryExpensiveClass? by WeakReferenceDelegate<MyMemoryExpensiveClass>()

        fun doWithReference(block: (MyMemoryExpensiveClass) -> Unit) {
            reference?.let(block)
        }
    }

    init {
        reference = this
    }
}