interface InputDevice { //輸入設備接口
fun input(event: Any) //輸入的方法
}
interface USBInputDevice: InputDevice //user輸入設備接口
interface BLEInputDevice: InputDevice //藍牙輸入設備接口
interface OpticalMouse //光電鼠標接口
abstract class USBMouse(val name: String): USBInputDevice, OpticalMouse { //usb鼠標
override fun input(event: Any) {
}
override fun toString(): String {
return name
}
}
class LogitechMouse : USBMouse("羅技鼠標") {
}
class Computer { //電腦類
fun addUSBInputDevice(inputDevice: USBInputDevice) { //插入usb輸入設備
println("add usb input device: $inputDevice")
}
fun addBLEInputDevice(inputDevice: BLEInputDevice) { //插入藍牙輸入設備
println("add ble input device: $inputDevice")
}
fun addInputDevice(inputDevice: InputDevice) { //插入輸入設備
when (inputDevice) {
is BLEInputDevice -> {
addBLEInputDevice(inputDevice)
}
is USBInputDevice -> {
addUSBInputDevice(inputDevice)
}
else -> {
throw IllegalArgumentException("輸入設備類型不支持")
}
}
}
}
fun main(args: Array<String>) {
val computer = Computer() //新建電腦
val mouse = LogitechMouse() //新建羅技鼠標
computer.addInputDevice(mouse) //把鼠標添加到電腦上
}

運行結果