Guest User

Untitled

a guest
Sep 12th, 2021
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.16 KB | None | 0 0
  1. <?php
  2.  
  3. interface Type
  4. {
  5.     public function getType(): string;
  6. }
  7.  
  8. final class Water implements Type
  9. {
  10.     public function getType(): string
  11.     {}
  12. }
  13.  
  14. final class Milk implements Type
  15. {
  16.     public function getType(): string
  17.     {}
  18. }
  19.  
  20. final class Coffee implements Type
  21. {
  22.     public function getType(): string
  23.     {}
  24. }
  25.  
  26. final class ProductFactory
  27. {
  28.     /**
  29.      * @var array<string, callable(): Type>
  30.      */
  31.     private array $factories;
  32.    
  33.     /**
  34.      * @param array<string, callable(): Type> $factories
  35.      */
  36.     public function __construct(array $factories)
  37.     {
  38.         $this->factories = $factories;
  39.     }
  40.  
  41.     public function create(string $type): Type
  42.     {
  43.         if (!isset($this->factories[$type])) {
  44.             throw new InvalidArgumentException();
  45.         }
  46.  
  47.         return ($this->factories[$type])();
  48.     }
  49. }
  50.  
  51. $factory = new ProductFactory([
  52.     'coffee' => static function (): Type {
  53.         return new Coffee();
  54.     },
  55.     'milk' => static function (): Type {
  56.         return new Milk();
  57.     },
  58.     'water' => static function (): Type {
  59.         return new Water();
  60.     },
  61. ]);
  62.  
  63. $factory->create('coffee');
Advertisement
Add Comment
Please, Sign In to add comment