1.7. Simple Factory

1.7.1. Purpose

SimpleFactory is a simple factory pattern.

It differs from the static factory because it is not static.Therefore, you can have multiple factories, differently parameterized, you can subclass it and you can mock it.It always should be preferred over a static factory!

1.7.2. UML Diagram

Alt SimpleFactory UML Diagram

1.7.3. Code

You can also find this code on GitHub

SimpleFactory.php

  1. <?php
  2.  
  3. namespace DesignPatterns\Creational\SimpleFactory;
  4.  
  5. class SimpleFactory
  6. {
  7. public function createBicycle(): Bicycle
  8. {
  9. return new Bicycle();
  10. }
  11. }

Bicycle.php

  1. <?php
  2.  
  3. namespace DesignPatterns\Creational\SimpleFactory;
  4.  
  5. class Bicycle
  6. {
  7. public function driveTo(string $destination)
  8. {
  9. }
  10. }

1.7.4. Usage

  1. $factory = new SimpleFactory();
  2. $bicycle = $factory->createBicycle();
  3. $bicycle->driveTo('Paris');

1.7.5. Test

Tests/SimpleFactoryTest.php

  1. <?php
  2.  
  3. namespace DesignPatterns\Creational\SimpleFactory\Tests;
  4.  
  5. use DesignPatterns\Creational\SimpleFactory\Bicycle;
  6. use DesignPatterns\Creational\SimpleFactory\SimpleFactory;
  7. use PHPUnit\Framework\TestCase;
  8.  
  9. class SimpleFactoryTest extends TestCase
  10. {
  11. public function testCanCreateBicycle()
  12. {
  13. $bicycle = (new SimpleFactory())->createBicycle();
  14. $this->assertInstanceOf(Bicycle::class, $bicycle);
  15. }
  16. }