Command Pattern - CoffeeScript Design Patterns

Posted 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) ->

  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: () ->

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

  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 lang=“coffee”] 1 2