Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- interface Type
- {
- public function getType(): string;
- }
- final class Water implements Type
- {
- public function getType(): string
- {}
- }
- final class Milk implements Type
- {
- public function getType(): string
- {}
- }
- final class Coffee implements Type
- {
- public function getType(): string
- {}
- }
- final class ProductFactory
- {
- /**
- * @var array<string, callable(): Type>
- */
- private array $factories;
- /**
- * @param array<string, callable(): Type> $factories
- */
- public function __construct(array $factories)
- {
- $this->factories = $factories;
- }
- public function create(string $type): Type
- {
- if (!isset($this->factories[$type])) {
- throw new InvalidArgumentException();
- }
- return ($this->factories[$type])();
- }
- }
- $factory = new ProductFactory([
- 'coffee' => static function (): Type {
- return new Coffee();
- },
- 'milk' => static function (): Type {
- return new Milk();
- },
- 'water' => static function (): Type {
- return new Water();
- },
- ]);
- $factory->create('coffee');
Advertisement
Add Comment
Please, Sign In to add comment