Command Pattern - CoffeeScript Design Patterns

By on

This is a classical approach to the command pattern. Like the Decorator Pattern it is a port from the examples in the GoF Design Patterns book.

[code lang=“coffee”]

Declares an interface for executing an operation

class Command
execute: () ->

  1. Asks the command to carry out the request

class Invoker
execute: (command) ->
command.execute()

  1. Knows how to perform the operations associated with carrying out a
  2. request. Any class may serve as a Receiver.

class Receiver
action1: () -> console.log "action1"
action2: () -> console.log "action2"

  1. * Defines a binding between a receiver object and an action
  2. * Implements execute() by invoking the corresponding operation(s) on Receiver

class ConcreteCommandA extends Command
constructor: (@receiver) ->
execute: () ->
@receiver.action1()

class ConcreteCommandB extends Command
constructor: (@receiver) ->
execute: () ->
@receiver.action2()

  1. Creates a ConcreteCommand object and sets its Receiver

class Client
@run: (action) ->
receiver = new Receiver()
ccmdA = new ConcreteCommandA receiver
ccmdB = new ConcreteCommandB receiver
invoker = new Invoker()
invoker.execute ccmdA if action is 1
invoker.execute ccmdB if action is 2
[/code]

Usage:

[code lang=“coffee”]
Client.run 1
Client.run 2
[/code]