JavaScript Strategy Pattern

Petr Kostelanský | 16 October 2017
We are going to take a look at Strategy Pattern in JavaScript with example how it could be useful in e-commerce web application.

We want to calculate shipping price according to order information like weight of items in order, sum price of items, size of items and so on.

Those information can be stored in variable or could be loaded from server, but this is not important in this example.

We have to create main class Shipping that will hold reference to concrete strategy and other methods and logic that will be shared.

To set concrete strategy we will call setCompany(...) to set concrete delivery company. There will be another public method getPrice(...) that will return calculated price for delivery company.

var Shipping = function(){
	this.company = "";
};
Shipping.prototype = {
    setCompany: function(company){
    	this.company = company;
    },
    getPrice: function(order){
    	return this.company.getPrice(order);
    }
};

Than we create delivery company with calculation logic:

var DHL = function(){
   this.getPrice = function(order){
      // calculate price according to order
      return 25;
  }
};

At the end we create Shipping class instance, set strategy class (delivery company) and call getPrice(...) that will return shipping price for concrete delivery company according to order state:

var shipping = new Shipping();

shipping.setCompany(new DHL());
var dhlPrice = shipping.getPrice(order);

And there is entire example:

var Shipping = function(){
	this.company = "";
};
Shipping.prototype = {
        setCompany: function(company){
    	this.company = company;
    },
    getPrice: function(order){
    	return this.company.getPrice(order);
    }
};

var DHL = function(){
    this.getPrice = function(order){
  	// calculate price according to order
    return 25;
  }
};

var UPS = function(){
    this.getPrice = function(order){
  	// calculate price according to order
    return 30;
  }
};

var order = {weight: 250};

var shipping = new Shipping();

shipping.setCompany(new DHL());
var dhlPrice = shipping.getPrice(order);
alert("DHL price: " + dhlPrice);

shipping.setCompany(new UPS());
var upsPrice = shipping.getPrice(order);
alert("UPS price: " + upsPrice);
Loading ads...