Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // The Strategy Pattern allows for the dynamic specification of a method for getting things done.
- //Strategy pattern allows you to move behavior into separate class which is good by SOLID principle 'S' - single responsibility.
- /*
- Strategy pattern allows you to move behavior into separate class which is good by SOLID principle 'S' - single responsibility. Image that you need to learn robot or human to 'bark' - you don't need to make them inherit animal base class. And you also don't need to implement barking in each class.
- Having all properties in base class is also not good as it is against SOLID 'L' - Liskou substitution. What if monkey don't need to bark which is implemented in base animal class?
- Strategy pattern allows you to design code accordingly to SOLID 'I' - Interface segregation - just make IAnimalAction interface make many implementations of barking and assign IAnimalAction property to desired animal classes (as property or as one more interface to implement)
- Strategy also helps with SOLID 'D' - you can inject desired animal strategy (barking, flying) without having each animal even know about it
- */
- // can use function or class (Fedex or USPS)
- function Fedex(pkg) {
- this.calculate = () => {
- return 2.45
- }
- }
- function UPS(pkg) {
- this.calculate = () => 1.24
- }
- class USPS {
- calculate () {
- return 3.15
- }
- }
- class Shipping {
- constructor() {
- this.company = ''
- }
- setStrategy(company) {
- this.company = company
- }
- calculate(pkg) {
- console.log('this.company', JSON.stringify(this.company))
- return this.company.calculate(pkg)
- }
- }
- const fedex = new Fedex();
- const ups = new UPS();
- const usps = new USPS();
- const shipping = new Shipping()
- const pkg = {
- from: "Alabama",
- to: "Georgia",
- weight: 1.56
- }
- shipping.setStrategy(fedex)
- console.log("Fedex:", shipping.calculate(pkg))
- shipping.setStrategy(ups)
- console.log("UPS:", shipping.calculate(pkg))
- shipping.setStrategy(usps)
- console.log("USPS:", shipping.calculate(pkg))
Advertisement
Add Comment
Please, Sign In to add comment