mituri

Wzorzec Strategy

Feb 14th, 2021
1,215
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // The Strategy Pattern allows for the dynamic specification of a method for getting things done.
  2. //Strategy pattern allows you to move behavior into separate class which is good by SOLID principle 'S' - single responsibility.
  3. /*
  4.     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.
  5.  
  6. 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?
  7.  
  8. 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)
  9.  
  10. Strategy also helps with SOLID 'D' - you can inject desired animal strategy (barking, flying) without having each animal even know about it
  11. */
  12.  
  13. // can use function or class (Fedex or USPS)
  14. function Fedex(pkg) {
  15.     this.calculate = () => {
  16.         return 2.45
  17.     }
  18. }
  19.  
  20. function UPS(pkg) {
  21.     this.calculate = () => 1.24
  22. }
  23.  
  24.  
  25. class USPS {
  26.     calculate () {
  27.         return 3.15
  28.   }
  29. }
  30.  
  31.  
  32. class Shipping {
  33.     constructor() {
  34.       this.company = ''  
  35.   }
  36.  
  37.   setStrategy(company) {
  38.     this.company = company
  39.   }
  40.  
  41.   calculate(pkg) {
  42.     console.log('this.company', JSON.stringify(this.company))
  43.     return  this.company.calculate(pkg)
  44.   }
  45. }
  46.  
  47. const fedex = new Fedex();
  48. const ups = new UPS();
  49. const usps = new USPS();
  50.  
  51. const shipping = new Shipping()
  52. const pkg = {
  53.     from: "Alabama",
  54.   to: "Georgia",
  55.   weight: 1.56
  56. }
  57.  
  58. shipping.setStrategy(fedex)
  59. console.log("Fedex:", shipping.calculate(pkg))
  60.  
  61. shipping.setStrategy(ups)
  62. console.log("UPS:", shipping.calculate(pkg))
  63.  
  64. shipping.setStrategy(usps)
  65. console.log("USPS:", shipping.calculate(pkg))
  66.  
Advertisement
Add Comment
Please, Sign In to add comment