Skip to content

Instantly share code, notes, and snippets.

@matthewjackowski
Last active December 20, 2015 08:55
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 matthewjackowski/1256ea75fce704675426 to your computer and use it in GitHub Desktop.
Save matthewjackowski/1256ea75fce704675426 to your computer and use it in GitHub Desktop.
Refactor to Strategy in Javascript
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
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