Реализации на Kotlin

Mediator

Общая реализация на языке Kotlin

Реализация класса медиатора

class SmartHomeMediator {
    private val devices = mutableListOf<SmartHomeDevice>()

    fun add(device: SmartHomeDevice) {
        devices.add(device)
        device.mediator = this
    }

    fun send(message: Message) {
        message.markSent()
        val currentMsgState = message.messageState
        require(currentMsgState is MessageState.Sent)
        println("${message.sender.name} send the message: ${message.content} at time: ${currentMsgState.timeSent}")
        devices
            .filter { smartHomeDevice ->  smartHomeDevice.deviceType == message.recipientType }
            .forEach { smartHomeDevice ->
                message.markReceived()
                smartHomeDevice.receive(message)
            }
    }
}

Реализация класса сообщений

class Message(
    val sender: SmartHomeDevice,
    val recipientType: DeviceType,
    val content: String
) {
    private var _messageState: MessageState = MessageState.Initial
    val messageState: MessageState
        get() = _messageState

    fun markSent() {
        val currentState = messageState
        if (currentState is MessageState.Initial) {
            _messageState = MessageState.Sent()
        } else {
            error("Illegal state for sending message: $currentState")
        }
    }

    fun markReceived() {
        val currentState = messageState
        if (currentState is MessageState.Sent) {
            _messageState = MessageState.Received(
                timeSent = currentState.timeSent
            )
        } else {
            error("Illegal state for receiving message: $currentState")
        }
    }
}

Реализация классов устройств

abstract class SmartHomeDevice(val name: String) {
    abstract val deviceType: DeviceType
    var mediator: SmartHomeMediator? = null

    abstract fun send(message: Message)
    abstract fun receive(message: Message)
}

Main

fun main() {
    val smartCoffeeMachine = SmartCoffeeMachine("Coffee Machine")
    val smartLivingRoomLight = SmartLight("Living Room Light")
    val smartKitchenLight1 = SmartLight("Kitchen Light1")
    val smartKitchenLight2 = SmartLight("Kitchen Light2")
    val smartHallwayLight = SmartLight("Hallway Light")
    val smartTV = SmartTv("Living Room TV")

    println("The owner of the house is back!")
    val houseMediator = SmartHomeMediator()
    houseMediator.add(smartHallwayLight)
    houseMediator.add(smartKitchenLight1)
    houseMediator.add(smartKitchenLight2)
    houseMediator.add(smartLivingRoomLight)
    houseMediator.add(smartCoffeeMachine)
    houseMediator.add(smartTV)

    smartHallwayLight.send(Message(smartHallwayLight, DeviceType.TV, "Set light on in house!"))
    smartKitchenLight1.send(Message(smartKitchenLight1, DeviceType.COFFEE_MACHINE, "Set light on! Let's make coffee"))

    val list = listOf(1, 2, 3)
    list.indexOf(1)
}

Last updated

Was this helpful?