Created
July 6, 2022 21:00
-
-
Save wolivera/5ff4fff73c9f7085ad2de41a66ad3637 to your computer and use it in GitHub Desktop.
GoF Strategy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Shipping { | |
constructor() { | |
this.method = ""; | |
} | |
setStrategy (method) { | |
this.method = method; | |
} | |
calculate (box) { | |
return this.method.calculate(box); | |
} | |
}; | |
class Air { | |
calculate (box) { | |
// calculations... | |
return "$45.95"; | |
} | |
} | |
class Sea { | |
calculate (box) { | |
// calculations... | |
return "$39.40"; | |
} | |
} | |
class Land { | |
calculate (box) { | |
// calculations... | |
return "$43.20"; | |
} | |
}; | |
const box = { from: "76712", to: "10012", weigth: "lkg" }; | |
// the 3 strategies | |
const air = new Air(); | |
const sea = new Sea(); | |
const land = new Land(); | |
const shipping = new Shipping(); | |
shipping.setStrategy(air); | |
console.log("Air Strategy: " + shipping.calculate(box)); | |
shipping.setStrategy(sea); | |
console.log("Sea Strategy: " + shipping.calculate(box)); | |
shipping.setStrategy(land); | |
console.log("Land Strategy: " + shipping.calculate(box)); | |
// Air Strategy: $45.95 | |
// Sea Strategy: $39.40 | |
// Land Strategy: $43.20 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment