Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Car
- {
- private const FACTORY_CLASSES = [
- CarFactory::class,
- ];
- /** @var iterable|AbstractCarFactory[] */
- private iterable $factories;
- /**
- * @param iterable|AbstractCarFactory[] $factories
- */
- public function __construct(iterable $factories)
- {
- $this->factories = $factories;
- }
- public static function get(string $car): CarInterface
- {
- $factory = new self(self::getDefaultFactories());
- return $factory->create($car);
- }
- public function create(string $car): CarInterface
- {
- foreach ($this->factories as $factory) {
- if ($factory->supports($car)) {
- return $factory->create($car);
- }
- }
- throw new InvalidArgumentException(sprintf('No car supports the given name "%s".', $car));
- }
- public static function getDefaultFactories(): Generator
- {
- foreach (self::FACTORY_CLASSES as $factoryClass) {
- if (!class_exists($factoryClass)) {
- continue;
- }
- yield new $factoryClass();
- }
- }
- }
- Car::get('red');
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement