如何将Android类转换为Singleton对象(Kotlin)

发布于 2025-01-20 16:09:38 字数 401 浏览 1 评论 0原文

目前,我有一个数据库管理器类,它处理对数据库的所有操作,如下所示:

class DatabaseManager(val context: Context) {
    private val db = Firebase.firestore
    //Other functions, etc.
}

它利用不同活动传入的上下文来对数据库执行功能。问题是,每个需要数据库函数的活动都必须首先实例化这个管理器类,然后调用函数。我想利用Singelton设计模式来使所有活动仅使用该类的单个实例。我相信 kotlin 的对象可以做到这一点,但是我还需要能够将活动的上下文传递到这个管理器类中。如有任何帮助,我们将不胜感激,谢谢!

Currently, I have a database manager class that handles all operations to the database like this:

class DatabaseManager(val context: Context) {
    private val db = Firebase.firestore
    //Other functions, etc.
}

It makes use of the context passed in by different activities to perform functions to the database. The thing is, every single activity that requires database functions have to instantiate this manager class first, then call the functions. I would like to make use of the Singelton design pattern to make it such that all the activities will only use a single instance of the class. I believe kotlin's objects can do this, however I also need to be able to pass in the context of the activities into this manager class. Any assistance is appreciated, thank you!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

枕梦 2025-01-27 16:09:38

我建议不要那样做。单例的问题在于它们使代码难以测试,您不能伪造数据库。对于数据库,这是一个特别糟糕的问题,因为设置所有正确的虚假数据可能会很痛苦。相反,看一下注射。它可以做同样的事情(在每个需要它的每个人之间共享一个实例),但是它可以管理全球状态,而不是通过静态参考来管理该类别,而是通过静态参考来管理它,将其传递给(通常是通过构造函数),它。这使得在需要时可以轻松提供替代或模拟数据库。注射曾经有点痛苦,但是刀柄使它如今变得容易得多。

I would recommend not doing that. The problem with Singletons is that they make code hard to test, you can't fake out the database. And for a database this is a particularly bad problem, as setting up all the right fake data can be painful. Instead, take a look at injection. It can do the same thing (make a single instance shared between everyone who needs it), but it manages that global state rather than having the classes themselves manage it via a static reference, passing it in (generally via the constructor) to whoever needs it. This makes it easy to provide an alternative or mock database when needed for testing. Injection used to be a bit painful to set up, but Hilt makes it a lot easier these days.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文