The command pattern is used to express a request, including the call to be made and all of its required parameters, in a command object. The command may then be executed immediately or held for later use.
Set up:
- Command Interface: Define the interface of various commands
- Concrete Command: Define behaviors of different commands
- Command Processor: Accept and execute commands
- Client Code
Example 1:
// Step 4: Client code
fun main(args: Array<String>) {
CommandProcessor()
.addOrder(OrderCoffee())
.addOrder(OrderTea())
.executeOrders()
}
// Step 1: Command Interface
interface Order{
fun order()
fun serve()
}
// Step 2: Concrete order classes
class OrderCoffee: Order{
override fun order() {
println("Please give me a cup of coffee.")
}
override fun serve() {
println("Here is you coffee.")
}
}
class OrderTea: Order{
override fun order() {
println("Please give me a cup of tea.")
}
override fun serve() {
println("Here is your tea.")
}
}
// Step 3: Invoker (Command Processor)
class CommandProcessor{
val orders = ArrayList<Order>()
fun addOrder(order: Order): CommandProcessor = apply{
orders.add(order)
}
fun executeOrders(): CommandProcessor = apply{
for (order in orders) {
order.order()
order.serve()
}
}
}
/**
prints
Please give me a cup of coffee.
Here is you coffee.
Please give me a cup of tea.
Here is your tea.
**/
Example 2:
// Step 4: Client code
fun main(args: Array<String>) {
with(DoggyBrain()){
receive(Sit())
receive(StandUp())
receive(RollOver())
execute()
}
}
// Step 1: Command interface
interface DogCommands{
fun action()
}
// Step 2: Concrete commands
class Sit: DogCommands{
override fun action() {
println("Good doggy, sit put!")
}
}
class StandUp: DogCommands{
override fun action() {
println("Good doggy, stand up!")
}
}
class RollOver: DogCommands{
override fun action() {
println("Good doggy, roll over!")
}
}
// Step 3: CommandProcessor
class DoggyBrain{
val commands = ArrayList<DogCommands>()
fun receive(command: DogCommands){
commands.add(command)
println(command.javaClass.simpleName + " in queue...")
}
fun execute(){
for (command in commands)
command.action()
}
}
/**
prints
Sit in queue...
StandUp in queue...
RollOver in queue...
Good doggy, sit put!
Good doggy, stand up!
Good doggy, roll over!
**/
```