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/70a38ae46b034ae8f056 to your computer and use it in GitHub Desktop.
Save jcrubino/70a38ae46b034ae8f056 to your computer and use it in GitHub Desktop.
Command Pattern Continued
/*
Command Pattern Continued
Adapted from https://en.wikipedia.org/wiki/Command_pattern#JavaScript
& http://www.onjava.com/pub/a/onjava/2006/04/05/ajax-mutual-exclusion.html
Application: Wallace Variation for Lamports Bakery Algorithm for implementing mutex in javascript
*/
/* The Invoker function */
var Invoke = function(){
var _commands = [];
this.id = 0;
this.storeAndExecute = function(command){
_commands.push(command);
command.execute();
++this.id;
console.log(this.id)
}
}
/* 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 client1 = new Invoke();
var client2 = new Invoke();
client1.storeAndExecute(stateOne);
client2.storeAndExecute(stateOne);
client1.storeAndExecute(stateZero);
client2.storeAndExecute(stateZero);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment