Kotlin command pattern

How to write a command pattern in Kotlin

An example of a command pattern in Kotlin.

Table of contents for design patterns in Kotlin

In object-oriented programming, the command pattern is a behavioral design pattern in which an object is used to encapsulate all information needed to perform an action or trigger an event at a later time. This information includes the method name, the object that owns the method and values for the method parameters. Wikipedia

Example:

Command

interface Command {
    fun execute()
}

CommandProcessor

class CommandProcessor {
    private val queue: Queue<Command> = LinkedList<Command>()

    fun add(command: Command) = queue.add(command)

    fun processCommands() {
        generateSequence { queue.poll() }.forEach { it.execute() }
    }
}

CreateFileCommand

class CreateFileCommand(private val filename: String): Command {
    override fun execute() {
        println("Create file: $filename")
    }
}

EmailSendCommand

class EmailSendCommand(private val to: String): Command {
    override fun execute() {
        println("Send email: $to")
    }
}

Usage:

fun main() {
    CommandProcessor().apply {
        add(CreateFileCommand("Hermes.sh"))
        add(EmailSendCommand("mark.watney@mars.universe"))
    }.processCommands()
}

Result

Create file: Hermes.sh
Send email: mark.watney@mars.universe