Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Kotlin 科特林最佳方法_Kotlin_Inheritance_Design Patterns - Fatal编程技术网

Kotlin 科特林最佳方法

Kotlin 科特林最佳方法,kotlin,inheritance,design-patterns,Kotlin,Inheritance,Design Patterns,我有一个函数fetchDetails(),它应该使用客户端检查id,确定它是哪种类型的设备(a、B、C),然后执行一系列操作来构造适当类型的设备细节,然后返回它。对于这个任务,什么是好的设计方法?我不认为一套if-else(如下)语句是正确的方法。DeviceA,DeviceB,DeviceC将比addInfo有更多的价值,我在这里只包含了这么多,以保持简单 fun fetchDetails(id: deviceId): DeviceDetails? { //construct

我有一个函数
fetchDetails()
,它应该使用客户端检查id,确定它是哪种类型的设备(a、B、C),然后执行一系列操作来构造适当类型的设备细节,然后返回它。对于这个任务,什么是好的设计方法?我不认为一套if-else(如下)语句是正确的方法。DeviceA,DeviceB,DeviceC将比addInfo有更多的价值,我在这里只包含了这么多,以保持简单

fun fetchDetails(id: deviceId): DeviceDetails? {
        //construct details depending on whether device is of type A, B, C and return deviceA, 
          deviceB or deviceC
        if(client.typeOf(id) == A)
           return constructDetailsA(id)
        if(client.typeOf(id) == B)
           return constructDetailsB(id)
        .....
    }

您是否考虑过在时使用
@Stachu所以,决定这个设备比我在这里展示的要简单一些。它更像是
client.getModel(id).contains(“DeviceA”)
。这不适合什么时候,对吗?不一定,你可以尝试这样的方法。我认为你可以使用工厂模式。你的代码被定向到
生成器模式
你考虑过什么时候使用
@Stachu所以,决定这个设备比我在这里展示的要简单一些。它更像是
client.getModel(id).contains(“DeviceA”)
。这不适合什么时候,对吗?不一定,你可以尝试这样的方法。我认为你可以使用工厂模式。你的代码直接指向
builder模式
class DetailFetcher(private val client: clientWrapper) {

    fun fetchDetails(id: deviceId): DeviceDetails? {
        //construct details depending on whether device is of type A, B, C and return deviceA, 
          deviceB or deviceC
    }

}

sealed class DeviceDetails
data class DeviceA(val addInfo: String) : DeviceDetails()
data class DeviceB(val addInfo: String) : DeviceDetails()
data class DeviceC(val addInfo: String) : DeviceDetails()