首页 > 解决方案 > 如何拥有一个只能由另一个特定类实例化的类

问题描述

我想要一个只能由另一个类实例化的类。我知道我必须将其设为constructor私有,否则每个人都可以实例化它。

class Root private constructor() {
}

class RootMaker: Application() {
    fun createRoot() = Root()
} // but this doesn't work because Root's constructor is private

一种解决方法是使类成为maker类的内部Root类。

class Root private constructor() {

    class RootMaker: Application() {
        fun createRoot() = Root()
    } 
}

但我真的不想这样做,因为 maker 类是我application在 android 中的类。那么更好的方法是什么?

标签: javaandroidkotlin

解决方案


如果你只想要一个对象的一个​​实例,你可以object在 Kotlin 中使用关键字。它实现Singleton了模式:

class App : Application {
    
    val root = Root

}

object Root {
    fun createObject(): Any {}
}

Root现在我们可以通过类中的属性App或通过类来访问类的一个实例RootRoot.createObject()

更新:

要实现只有一个特定类可以访问的单例,我们可以使用接口并将其实现隐藏在该特定类(制造商类)中:

interface IRoot {
    // ... methods of creation different objects for dependency injection
}

class App : Application {

    val root: IRoot = Root

    // hide implementation of `IRoot` interface in `App` class
    private object Root : IRoot {

        // ... implementation of methods of creation different objects for dependency injection
    }
}

推荐阅读