...

/

Implementation of Command Pattern

Implementation of Command Pattern

Learn about the Task pattern and different implementations of the Command pattern.

We'll cover the following...

Now, we’re going to explore a couple of different implementations of the Command pattern in more detail, just to get an idea of its scope.

The Task pattern

We can start off with the most basic and trivial implementation of the Command pattern: the Task pattern. The easiest way in JavaScript to create an object representing an invocation is, of course, by creating a closure around a function definition or a bound function.

function createTask(target, ...args) {
return () => {
target(...args)
}
}

This is (mostly) equivalent to doing the following:

const task = target.bind(null, ...args)

This shouldn’t look new at all. This technique allows us to use a separate component to control and schedule the execution of our tasks, which is essentially equivalent to the invoker of the Command pattern.

A more complex command

Let’s now work on a more articulated example leveraging the Command pattern. This time, we want to support undo and serialization. Let’s start ...