Last active
December 20, 2015 08:55
-
-
Save matthewjackowski/1256ea75fce704675426 to your computer and use it in GitHub Desktop.
Refactor to Strategy in 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
var message = require('./lib/zmessage'); | |
var Strategy = function(f) { | |
this.send = f; | |
}; | |
Strategy.prototype.execute = function(m) { | |
this.send(m); | |
}; | |
var A = new Strategy(function(m) { | |
console.log('Type found, take action on message type A'); | |
message.A.inspect(m); | |
}); | |
module.exports = { | |
switchStrategy: function(strategy) { | |
this.strategy = strategy; | |
}, | |
invokeStrategy: function(m) { | |
this.strategy.execute(m); | |
}, | |
}; | |
msg = message.A.create(); | |
myapp = module.exports; | |
myapp.switchStrategy(A); | |
myapp.invokeStrategy(msg); | |
myapp.switchStrategy(Z); // Not defined error |
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
module.exports = { | |
A: { | |
name: 'Message Type A', | |
create: function() { | |
return ({type: 'A',messages: []}); | |
}, | |
inspect: function(m) { | |
var out = 'type: A | messages: [m.messages]'; | |
out = (m.messages.length < 1)? | |
out.replace('[m.messages]','empty list'): | |
out.replace('[m.messages]',m.messages); | |
console.log(out); | |
}, | |
}, | |
B: { | |
name: 'Message Type B', | |
create: function() { | |
return ({type: 'B',header: {},data: {}}); | |
}, | |
inspect: function(m) { | |
var out = 'type: B | messages: [m.messages]'; | |
out = (m.messages.length < 1)? | |
out.replace('[m.messages]','empty list'): | |
out.replace('[m.messages]',m.messages); | |
console.log(out); | |
}, | |
}, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment