在不实现的情况下操纵抽象 class

Manipulating abstract class without implementing

我有一个 Runnable 抽象 class winch 代表对等点的套接字。

我必须保留我创建的所有套接字的引用,所以我选择将其包装到管理器中 class 以创建套接字并将它们添加到列表中

import java.util.concurrent.Executors

internal interface SocketInterface {
    fun onSocketConnected()
}

abstract class Socket(val host: String) : Runnable, SocketInterface {
    override fun run() {
        //Connected
        onSocketConnected()
    }
}

abstract class SocketManager : SocketInterface {
    private val executorService = Executors.newSingleThreadExecutor()
    var sockets = mutableListOf<Socket>()

    fun addSocket(host: String) {
        //val socket = Socket(host)
        executorService.execute(socket)
        sockets.add(socket)
    }
}

class Main {
    val manager = object : SocketManager() {
        override fun onSocketConnected() {
            //Peer connected correctly
        }
    }
    //add new socket to manager
    manager.addSocket('google.com')

}

但是行

//val socket = Socket(host)

说抽象 class 无法实例化是错误的。

我希望我的经理在顶级应用程序(主)中实例化之前不关心实施

编辑: 我找到了一个临时解决方案,为 SocketManager

中的抽象方法 onSocketConnected 实现了默认值
abstract class SocketManager : SocketInterface {
    private val executorService = Executors.newSingleThreadExecutor()
    var sockets = mutableListOf<Socket>()

    override fun onSocketConnected() {/* Log.d('tag', 'uglySolution'*/}

    fun addSocket(host: String) {
        //val socket = Socket(host)
        executorService.execute(socket)
        sockets.add(socket)
    }
}

不过长得丑不标准

目前,我是这样解决问题的。

但我认为这不是正确的方法,如果您找到任何解决方案,请告诉我。

import java.util.concurrent.Executors

abstract class Socket(val host: String) : Runnable, SocketInterface {
    override fun run() {
        onAbstractSocketConnected()
    }
}
internal interface SocketInterface {
    fun onAbstractSocketConnected()
}


abstract class SocketManager : SocketInterface, SocketManagerInterface {
    private val executorService = Executors.newSingleThreadExecutor()
    var sockets = mutableListOf<Socket>()

    fun addSocket(host: String) {
        val socket = object : Socket(host){
            override fun onAbstractSocketConnected(){
                onSocketConnected()
            }
        }
        executorService.execute(socket)
        sockets.add(socket)
    }
}
internal interface SocketManagerInterface {
    fun onSocketConnected()
}

class Main {
    val manager = object : SocketManager() {
        override fun onSocketConnected() {
            //Override now
            Log.d("DEBUG", "socket is connected")
        }
    }
    //add new socket to manager
    manager.addSocket('google.com')
}