java - 如何拥有一个只能由另一个特定类实例化的类
问题描述
我想要一个只能由另一个类实例化的类。我知道我必须将其设为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 中的类。那么更好的方法是什么?
解决方案
如果你只想要一个对象的一个实例,你可以object
在 Kotlin 中使用关键字。它实现Singleton
了模式:
class App : Application {
val root = Root
}
object Root {
fun createObject(): Any {}
}
Root
现在我们可以通过类中的属性App
或通过类来访问类的一个实例Root
:Root.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
}
}
推荐阅读
- java - 在 Java 中,是否可以使用 super 关键字从子类中引用父类的静态变量?
- vb.net - 如何使 Vb.Net 登录表单允许多个用户使用存储在 .DAT 文件中的密码登录
- java - iText7 将 PDF 转换为 Tiff
- python - tl.models.vgg19 的问题(pretrained=True, end_with = 'pool4',mode='static')
- r - R:森林图与lsmean的平均值差异?
- reactjs - History.listen 没有在反应中触发
- python - 具有多个标签的 ImageDataGenerator
- json - 将 JSONObject 发送到服务器并获取 String volley
- swagger - 如何从 Avro 模式生成 OpenAPI Swagger
- elasticsearch - Elastic OR-options 它没有像我预期的那样工作