The core concept

The command pattern encapsulates a series of operations into a command object, which is then delivered to the recipient to execute. Thus decoupling the requester from the receiver. It looks something like this in code:

const dog = {
  bark: () = > {
    console.log('bark')}},// The method to build the command object
const createCommand = receiver= > {
  return {
    execute() {
      receiver.bark()
    },
  }
}

// Build a command object for barking
const barkCommand = createCommand(dog)

// The request is sent
button.onclick = () = > {
  barkCommand.execute()
}
Copy the code

This may seem like just making a simple problem more complicated, because the above function could have been done with the simpler code below:

const dog = {
  bark: () = > {
    console.log('bark')}},// The request is sent
button.onclick = () = > {
  dog.bark()
}
Copy the code

So why do we need command mode? Why add one more command object build?

The reason is that the built command objects have longer life cycles.

In addition to having the execute method to perform a particular operation, command objects can also be used with the undo method to undo an operation that has already been performed (which requires some additional initial data to be logged at execute). We can even push each command object on to a task stack after execution to implement a sequence of actions to reproduce and undo.

Extend the usage

For some event behaviors that need to be changed frequently, we can also use the change referenced by the execute method of the command object to replace the frequent event mounting and removal, thus reducing the system overhead. As in the following example:

const sayHi = () = > {
  console.log('hi')}const sayHello = () = > {
  console.log('hello')}// It needs to be removed and mounted
button.addEventListener('click', sayHi)
button.removeEventListener('click', sayHi)
button.addEventListener('click', sayHello)

const sayCommand = {
  execute: () = > {
    console.log('hi')}},// Only need to mount once
button.addEventListener('click'.() = > {
  sayCommand.execute()
})

sayCommand.execute = () = > {
  console.log('hello')}Copy the code