简体   繁体   English

使用kotlin创建数据库工厂

[英]Creating a DB factory using kotlin

So I'm trying to create a MongoDB factory with kotlin... but I think I don't really understand the concept of companion object very well because I can't even get this to compile: 所以我试图用kotlin创建一个MongoDB工厂...但是我想我不太了解companion object的概念,因为我什至无法编译它:

package org.jgmanzano.storage

import com.mongodb.MongoClient
import com.mongodb.MongoClientURI
import com.mongodb.client.MongoDatabase

class MongoConnectionFactory(private val connectionURI: String) {
    private var database: MongoDatabase

    init {
        val connectionString = MongoClientURI(connectionURI)
        val mongoClient = MongoClient(connectionString)
        database = mongoClient.getDatabase("paybotDB")
    }

    companion object {
        fun getDatabase() : MongoDatabase {
            return database
        }
    }
}

How would you guys achieve this? 你们将如何实现这一目标? My idea is to create what in Java would be a kind of factory method . 我的想法是在Java中创建一种工厂方法 I can't seem to get the syntax right tho. 我似乎无法正确理解语法。

Furthermore, would this be a correct approach to DB connection factories? 此外,这是数据库连接工厂的正确方法吗?

Move everything to the companion object, pass the connection URI to the getDatabase method. 将所有内容移动到伴随对象,将连接URI传递给getDatabase方法。 Companion objects get compiled as a static field inside the containing (outer class). 随播对象在包含(外部类)内部被编译为静态字段。 Since the field is static, it cannot access outer class's fields because the outer class is an instance. 由于该字段是静态的,因此它无法访问外部类的字段,因为外部类是实例。

I assume you want to cache database objects. 我假设您要缓存数据库对象。

class MongoConnectionFactory() {

    companion object {
        private var database: MongoDatabae? = null

        fun getDatabase(connectionURI: String) : MongoDatabase {
            if (database != null) {
                return database
            {
            val connectionString = MongoClientURI(connectionURI)
            val mongoClient = MongoClient(connectionString)
            database = mongoClient.getDatabase("paybotDB")
            return database
        }
    }
}

But then you don't need a companion object nested inside containing class. 但是然后,您不需要在包含类中嵌套的伴随对象。 You can create an object instead. 您可以改为创建一个对象。

object MongoConnectionFactory {
    private var database: MongoDatabae? = null

    fun getDatabase(connectionURI: String) : MongoDatabase {
        if (database != null) {
            return database
        {
        val connectionString = MongoClientURI(connectionURI)
        val mongoClient = MongoClient(connectionString)
        database = mongoClient.getDatabase("paybotDB")
        return database
    }
}

If you need multiple databases with different connection URIs then store them inside the hash table. 如果您需要具有不同连接URI的多个数据库,则将它们存储在哈希表中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM