gpt4 book ai didi

kotlin - Kotlin 中的私有(private)构造函数有什么用?

转载 作者:行者123 更新时间:2023-12-02 12:23:53 25 4
gpt4 key购买 nike

我是 Kotlin 的新手。我想问一下Kotlin中的private constructor是干什么用的? 类 DontCreateMe 私有(private)构造函数 () {/*...*/}。我的意思是如果我们不能创建它的实例应该是什么类?

最佳答案

好吧,评论中的答案是正确的,但是因为没有人写出完整的答案。我要试试看。

拥有私有(private)构造函数并不一定意味着对象不能被外部代码使用。这只是意味着外部代码不能直接使用它的构造函数,所以它必须通过类范围内公开的 API 来获取实例。由于此 API 在类范围内,因此它可以访问私有(private)构造函数。

最简单的例子是:

class ShyPerson private constructor() {
companion object {
fun goToParty() : ShyPerson {
return ShyPerson()
}
}
}

fun main(args: String) {
// outside code is not directly using the constructor
val person = ShyPerson.goToParty()

// Just so you can see that you have an instance allocated in memory
println(person)
}

我见过的最常见的用例是实现单例模式,如 Mojtaba Haddadi 所述,其中外部代码只能访问该类的一个实例。

一个简单的实现是:

class Unity private constructor() {
companion object {
private var INSTANCE : Unity? = null

// Note that the reason why I've returned nullable type here is
// because kotlin cannot smart-cast to a non-null type when dealing
// with mutable values (var), because it could have been set to null
// by another thread.
fun instance() : Unity? {
if (INSTANCE == null) {
INSTANCE = Unity()
}
return INSTANCE
}
}
}

fun main(args: Array<String>) {
val instance = Unity.instance()
println(instance)
}

这经常被使用,这样消耗资源的类只被实例化一次,或者某些数据片段被整个代码库共享。

请注意,kotlin 使用 object keyword实现这种模式,具有线程安全的优点。还有一些开发人员考虑 Singletons to be an anti-pattern

私有(private)构造函数的另一个用例是实现 Builder patterns ,其中具有复杂初始化的类可以抽象为更简单的 API,因此用户不必处理笨重的构造函数。这other answer解决了它在 kotlin 中的用途。

我见过的现实生活中 kotlin 代码中最简单的用法之一是 Result implementation来自 stdlib,它用于更改对象的内部表示。

关于kotlin - Kotlin 中的私有(private)构造函数有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59336989/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com