Skip to content

Instantly share code, notes, and snippets.

@jcrubino
Last active August 29, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcrubino/5bd10e19fe7b661ad51c to your computer and use it in GitHub Desktop.
Save jcrubino/5bd10e19fe7b661ad51c to your computer and use it in GitHub Desktop.
Generic Command Pattern Javascript
/* Generic Command Pattern in Javascript */
/* Adapted from https://en.wikipedia.org/wiki/Command_pattern#JavaScript */
/* Application: Wallace Variation for Lamports Bakery Algorithm for implementing mutex in javascript */
/* The Invoker function */
var Invoke = function(){
var _commands = [];
this.storeAndExecute = function(command){
_commands.push(command);
command.execute();
}
}
/* Receiver function */
var Reciever = function(){
this.stateZero = function(){ console.log ('state 0') };
this.stateOne = function(){ console.log ('state 1') };
}
/* The StateZeroExecute command */
var StateZeroExecute = function(reciever){
this.execute = function() { reciever.stateZero() };
}
/* The StateOneExecute command */
var StateOneExecute = function(reciever){
this.execute = function() { reciever.stateOne() };
}
var StateMachine = new Reciever();
var stateOne = new StateOneExecute(StateMachine);
var stateZero = new StateZeroExecute(StateMachine);
var client = new Invoke();
client.storeAndExecute(stateOne);
client.storeAndExecute(stateZero);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment