1.9. Static Factory

1.9.1. Purpose

Similar to the AbstractFactory, this pattern is used to create series ofrelated or dependent objects. The difference between this and theabstract factory pattern is that the static factory pattern uses justone static method to create all types of objects it can create. It isusually named factory or build.

1.9.2. Examples

  • Zend Framework: Zend_Cache_Backend or _Frontend use a factorymethod create cache backends or frontends

1.9.3. UML Diagram

Alt StaticFactory UML Diagram

1.9.4. Code

You can also find this code on GitHub

StaticFactory.php

  1. <?php
  2.  
  3. namespace DesignPatterns\Creational\StaticFactory;
  4.  
  5. /**
  6. * Note1: Remember, static means global state which is evil because it can't be mocked for tests
  7. * Note2: Cannot be subclassed or mock-upped or have multiple different instances.
  8. */
  9. final class StaticFactory
  10. {
  11. /**
  12. * @param string $type
  13. *
  14. * @return FormatterInterface
  15. */
  16. public static function factory(string $type): FormatterInterface
  17. {
  18. if ($type == 'number') {
  19. return new FormatNumber();
  20. }
  21.  
  22. if ($type == 'string') {
  23. return new FormatString();
  24. }
  25.  
  26. throw new \InvalidArgumentException('Unknown format given');
  27. }
  28. }

FormatterInterface.php

  1. <?php
  2.  
  3. namespace DesignPatterns\Creational\StaticFactory;
  4.  
  5. interface FormatterInterface
  6. {
  7. }

FormatString.php

  1. <?php
  2.  
  3. namespace DesignPatterns\Creational\StaticFactory;
  4.  
  5. class FormatString implements FormatterInterface
  6. {
  7. }

FormatNumber.php

  1. <?php
  2.  
  3. namespace DesignPatterns\Creational\StaticFactory;
  4.  
  5. class FormatNumber implements FormatterInterface
  6. {
  7. }

1.9.5. Test

Tests/StaticFactoryTest.php

  1. <?php
  2.  
  3. namespace DesignPatterns\Creational\StaticFactory\Tests;
  4.  
  5. use DesignPatterns\Creational\StaticFactory\StaticFactory;
  6. use PHPUnit\Framework\TestCase;
  7.  
  8. class StaticFactoryTest extends TestCase
  9. {
  10. public function testCanCreateNumberFormatter()
  11. {
  12. $this->assertInstanceOf(
  13. 'DesignPatterns\Creational\StaticFactory\FormatNumber',
  14. StaticFactory::factory('number')
  15. );
  16. }
  17.  
  18. public function testCanCreateStringFormatter()
  19. {
  20. $this->assertInstanceOf(
  21. 'DesignPatterns\Creational\StaticFactory\FormatString',
  22. StaticFactory::factory('string')
  23. );
  24. }
  25.  
  26. /**
  27. * @expectedException \InvalidArgumentException
  28. */
  29. public function testException()
  30. {
  31. StaticFactory::factory('object');
  32. }
  33. }