Last active
August 29, 2015 14:10
-
-
Save jcrubino/5bd10e19fe7b661ad51c to your computer and use it in GitHub Desktop.
Generic Command Pattern Javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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