Instantly share code, notes, and snippets.

Embed
What would you like to do?
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