Guest User

Strategy design pattern example

a guest
Jan 14th, 2021
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.98 KB | None | 0 0
  1. <?php
  2.  
  3. interface Strategy {
  4.     public function calculate(array $criteria): array;
  5. }
  6.  
  7. class TwoThousandNineteenStrategy implements Stragety {
  8.     public function calculate(array $criteria): array
  9.     {
  10.         // query and calculation for 2019.
  11.     }
  12. }
  13.  
  14. class TwoThousandEighteenStrategy implements Stragety {
  15.     public function calculate(array $criteria): array
  16.     {
  17.         // query and calculation for 2018.
  18.     }
  19. }
  20.  
  21. class StrategyFactory
  22. {
  23.     public function create(int $year): Strategy
  24.     {
  25.         if ($year === 2018) {
  26.             return new TwoThousandEighteenStrategy();
  27.         }
  28.         if ($year === 2019) {
  29.             return new TwoThousandNineteenStrategy();
  30.         }
  31.        
  32.         throw new InvalidArgumentException('Missing strategy for given year');
  33.     }        
  34. }
  35.  
  36. $strategyFactory = new StrategyFactory();
  37.  
  38. foreach ($years as $year) {
  39.     $stategy = $strategyFactory->create($year);
  40.     resultOfTheYear = $strategy->calcule([]);
  41. }
Advertisement
Add Comment
Please, Sign In to add comment