Strategy Pattern in Javascript

With the Strategy pattern, your object is composed of a “strategy” object that can be swapped out for other strategy objects that adhere to the same interface (same method signatures). Each strategy object contains a different algorithm, and the algorithm that is ultimately used by the composite object for business logic is determined by whichever strategy object has been swapped in.

by Richard Lovell

HTML

<h3>Strategy Pattern in Javascript</h3>
<p>Check out the console for output.</p>

JavaScript

"use strict";

//Customer constructor class
function Customer(billingStrategy) {
    //list for storing drinks
    this.drinks = [];
    this.billingStrategy = billingStrategy;
}

Customer.prototype.add = function(price, quantity) {
    this.drinks.push(this.billingStrategy.getPrice(price * quantity));
};

Customer.prototype.printBill = function() {
    var sum = 0;
    for (var i = 0; i < this.drinks.length; i++) {
        sum += this.drinks[i];
    }
    console.log("Total due: " + sum);
    this.drinks = [];
};


// Define our billing strategy objects
var billingStrategies = {
    normal: {
        getPrice: function(rawPrice) {
            return rawPrice;
        }
    },
    happyHour: {
        getPrice: function(rawPrice) {
            return rawPrice * 0.5;
        }
    }
};

console.log("****Customer 1****");

var customer1 = new Customer(billingStrategies.normal);
customer1.add(1.0, 1);
customer1.billingStrategy = billingStrategies.happyHour;
customer1.add(1.0, 2);
customer1.printBill();
// New Customer
console.log("****Customer 2****");

var customer2 = new Customer(billingStrategies.happyHour);
customer2.add(0.8, 1);

// The Customer pays
customer2.printBill();

// End Happy Hour
customer2.billingStrategy = billingStrategies.normal;
customer2.add(1.3, 2);
customer2.add(2.5, 1);
customer2.printBill();