Skip to content

Brilliant Coding Blog

Be Brilliant

Refactoring to Strategy Pattern in Javascript

This is a quick example to show refactoring to a strategy pattern.

We will take a simple function that uses a case statement and refactor with the strategy pattern. Keep in mind this approach will also work with ‘if … else’ trees too!

In the example below we are using function ‘send’ to display information on different types of messages. It’s important to note that in the ‘switch’ implementation a string identifier has to be passed explicitly.

  send: function(t, m) {
    switch (t) {
      case message.A.name: {
        console.log('Type found, take action on message type A');
        message.A.inspect(m);
        break;
      }
      case message.B.name: {
        console.log('Type found, take action on message type B.');
        message.B.inspect(m);
        break;
      }
      default: {
        console.log('Type not found, return false');
        return false;
        break;
      }
    }
    return true;
  },

An example invocation for this approach is:

msg = message.A.create();
console.log(myapp.send('Message Type A',msg));
console.log(myapp.send('Invalid Type',msg));

Now let’s refactor to our strategy pattern:

First we will need to create a ‘Strategy’ function that will implement the ‘send’ call. Next will be create a message ‘A’ and ‘B’ strategies to allow us to switch our strategy. Last we will add 2 new functions to ‘switch’ and ‘invoke’ our strategy function.

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);
  return true;
});

var B = new Strategy(function(m) {
  console.log('Type found, take action on message type B');
  message.B.inspect(m);
  return true;
});

myapp = {
  switchStrategy: function(strategy) {
  this.strategy = strategy;
},

  invokeStrategy: function(m) {
  this.strategy.execute(m);
},

};

The invocation of this now looks like this:

msg = message.A.create();
myapp.switchStrategy(A);
myapp.invokeStrategy(msg);
myapp.switchStrategy(Z); // Not defined error

The final version of this code can be found in a Gist here.

Refactoring to Strategy Pattern in Javascript