Command 

The command pattern is used to encapsulate required information in order to perform an action or start a process. The data is therefore put into an object that is passed to an executor. It's worth mentioning that execution of commands can also be delayed if this is necessary. The following diagram shows how this pattern can be implemented:

The preceding diagram contains the UserCommand interface, which is implemented by the CreateUserCommand and DeleteUserCommand classes. A constructor of UserCommand takes an instance of the User class and a certain implementation of the UserCommand interface, then encapsulates an operation with a user.

The following example performs operations using the User class:

data class User(val firstName: String, val lastName: String)

UserCommand is a base interface for commands related to a user:

interface UserCommand {
val user: User
fun execute()
}

This interface obliges classes that implement it to initialize the user property and override the execute method. Classes that perform certain commands may look something like this:

class CreateUserCommand(override val user: User) : UserCommand {
override fun execute() {
println("Creating...")
}
}

class DeleteUserCommand(override val user: User) : UserCommand {
override fun execute() {
println("Deleting...")
}
}

The Executor class encapsulates a queue with commands and contains the addCommand and execute methods, as follows:

class Executor {
private val queue = LinkedList<UserCommand>()

fun addCommand(command: UserCommand) {
queue.add(command)
}

fun execute() {
queue.forEach { it.execute() }
}
}

Use of the Executor pattern might look as follows:

fun main(args: Array<String>) {
val executor = Executor()
val user = User("Igor", "Kucherenko")
//..........
executor.addCommand(CreateUserCommand(user))
//..........
executor.addCommand(DeleteUserCommand(user))

executor.execute()
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.254.151