concept

The command pattern encapsulates procedural requests within the Execute method of a command object.

example

For example, there is a business logic that says “the user clicks a button to refresh the menu catalog.” Procedural invocation:

const MenuBar = {
  refresh: function () {
    console.log('Refresh menu directory'); }};const bindClick = () = > {
  button.onclick = () = > {
    MenuBar.refresh()
  }
}
bindClick()
Copy the code

Encapsulate as a command object:

// Encapsulates the command object
var RefreshMenuBarCommand = function (receiver) {
  this.receiver = receiver;
};
RefreshMenuBarCommand.prototype.execute = function () {
  this.receiver.refresh();
};
// Install command
const bindClick = (command) = > {
  button.onclick = () = > {
    command.execute();
  }
}
bindClick(new RefreshMenuBarCommand(MenuBar))
Copy the code

You can see that it decouples request senders and receivers by passing command objects. But it’s also clear: simple things get complicated.

Actually, you don’t have to do this in javascript. The command pattern is an object-oriented substitute for the callback function.

Let’s use the callback function directly:

const bindClick = ( callback ) = >{
  button.onclick = () = >{ callback(); }}; bindClick(MenuBar.refresh)Copy the code

This is also decoupled.

In fact, because of the preconception of callback, it is difficult for the front-end to appreciate the benefits of command mode, and indeed it is. Its encapsulated, decoupled, easily extensible capabilities and benefits are also available through callback + closures or publish-subscribe patterns.

In short, the command pattern is the essence of callbacks in the name of object orientation. In JavaScript, you can take its meaning, but you don’t have to use its form.

extract

The theme of design patterns is always to separate things that don’t change from things that change. — JavaScript Design Patterns and Development Practices