在代码 A 中,我定义了两个标准数据,但我认为这段代码就像aBluetoothDef?.let{BluetoothHelper(mContext).setBluetooth(it)}
一样,很难扩展。
在代码B中,我为数据类添加函数,我不知道是否有向数据类添加函数的好方法,但我可以使用相同的方法,例如aBluetoothDef?.set(mContext)
扩展。
你能告诉我代码 A 和代码 B 之间哪个更好吗?
而且,我认为Code B将数据和业务逻辑混合成一个大类,这不是一个好方法,对吧?
代码 A
class BluetoothHelper(val mContext: Context) {
fun setBluetooth(aBluetoothDef: BluetoothDef): Unit{
}
}
class WiFiHelper(val mContext: Context) {
fun setWiFi(aWiFiDef: WiFiDef): Unit{
}
}
interface DeviceDef
data class BluetoothDef(
val isChecked: Boolean = true,
val status: Boolean = false
) : DeviceDef
data class WiFiDef(
val isChecked: Boolean = true,
val name: String,
val status: Boolean = false
) : DeviceDef
private fun restoreBackup(){
var aMDetail=DetailsHandler().getDetail(mListBackupItem[index]._id)
var aBluetoothDef= aMDetail?.getDevice<BluetoothDef>()
var aWiFiDef=aMDetail?.getDevice<WiFiDef>()
aBluetoothDef?.let{BluetoothHelper(mContext).setBluetooth(it)}
aWiFiDef?.let { WiFiHelper(mContext).setWiFi(it) }
}
代码 B
class BluetoothHelper(val mContext: Context) {
fun setBluetooth(aBluetoothDef: BluetoothDef): Unit{
}
}
class WiFiHelper(val mContext: Context) {
fun setWiFi(aWiFiDef: WiFiDef): Unit{
}
}
interface DeviceDef
data class BluetoothDef(
val isChecked: Boolean = true,
val status: Boolean = false
) : DeviceDef{
fun set(mContext: Context){
BluetoothHelper(mContext).setBluetooth(this)
}
}
data class WiFiDef(
val isChecked: Boolean = true,
val name: String,
val status: Boolean = false
) : DeviceDef {
fun set(mContext: Context){
WiFiHelper(mContext).setWiFi(this)
}
}
private fun restoreBackup(){
var aMDetail=DetailsHandler().getDetail(mListBackupItem[index]._id)
var aBluetoothDef= aMDetail?.getDevice<BluetoothDef>()
var aWiFiDef=aMDetail?.getDevice<WiFiDef>()
aBluetoothDef?.set(mContext)
aBluetoothDef?.set(mContext)
}
从语义上讲,
set()
并不是您实际正在做的事情的最佳命名。由于 Kotlin 支持扩展函数,因此您可以同时使用这两种方法。
data class BluetoothDef(
val isChecked: Boolean = true,
val status: Boolean = false
) : DeviceDef
fun BluetoothDef.with(context: Context) {
BluetoothHelper(context).setBluetooth(this)
}
我会选择这样的东西:
private fun restoreBackup(){
val deviceService = DeviceService(context);
val aMDetail=DetailsHandler().getDetail(mListBackupItem[index]._id)
deviceService.updateBluetooth(aMDetail.getDeviceDefinition<BluetoothDef>());
deviceService.updateWifi(aMDetail.getDeviceDefinition<WifiDef>())
}
我不明白你的问题。但我认为这对你的班级来说可能是更好的结构。
class DeviceHelper(){
var deviceDef = DeviceDef()
}
data class DeviceDef(val isChecked: Boolean = true,
val status: Boolean = false,
val isWifi: Boolean = false, //if true Wifi else Bluetooth
val name: String = "" //Bluetooth and Wireless both have name )
private fun restoreBackup(){
//Your calculation
}