Javascript Strategy

Jae Hoon Shin, 신재훈, Noah·2022년 1월 23일
0

Javascript Strategy

Here is the example

  • Shipping is the Context and the 3 shipping companies UPS, USPS, and Fedex are the Strategies.
  • The shipping companies (strategies) are changed 3 times and each time we calculate the cost of shipping.
  • In a real-world scenario the calculate methods may call into the shipper's Web service.
  • At the end we display the different costs.
var Shipping = function () {
    this.company = "";
};

Shipping.prototype = {
    setStrategy: function (company) {
        this.company = company;
    },

    calculate: function (package) {
        return this.company.calculate(package);
    }
};

var UPS = function () {
    this.calculate = function (package) {
        // calculations...
        return "$45.95";
    }
};

var USPS = function () {
    this.calculate = function (package) {
        // calculations...
        return "$39.40";
    }
};

var Fedex = function () {
    this.calculate = function (package) {
        // calculations...
        return "$43.20";
    }
};

function run() {

    var package = { from: "76712", to: "10012", weigth: "lkg" };

    // the 3 strategies

    var ups = new UPS();
    var usps = new USPS();
    var fedex = new Fedex();

    var shipping = new Shipping();

    shipping.setStrategy(ups);
    console.log("UPS Strategy: " + shipping.calculate(package));
    shipping.setStrategy(usps);
    console.log("USPS Strategy: " + shipping.calculate(package));
    shipping.setStrategy(fedex);
    console.log("Fedex Strategy: " + shipping.calculate(package));
}

If you run this code,
UPS Strategy: $45.95
USPS Strategy: $39.40
Fedex Strategy: $43.20

[reference] https://www.dofactory.com/javascript/design-patterns/strategy

profile
🇰🇷🇺🇸 #Back-End Engineer

0개의 댓글