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
1.9.4. Code
You can also find this code on GitHub
StaticFactory.php
- <?php
- namespace DesignPatterns\Creational\StaticFactory;
- /**
- * Note1: Remember, static means global state which is evil because it can't be mocked for tests
- * Note2: Cannot be subclassed or mock-upped or have multiple different instances.
- */
- final class StaticFactory
- {
- /**
- * @param string $type
- *
- * @return FormatterInterface
- */
- public static function factory(string $type): FormatterInterface
- {
- if ($type == 'number') {
- return new FormatNumber();
- }
- if ($type == 'string') {
- return new FormatString();
- }
- throw new \InvalidArgumentException('Unknown format given');
- }
- }
FormatterInterface.php
- <?php
- namespace DesignPatterns\Creational\StaticFactory;
- interface FormatterInterface
- {
- }
FormatString.php
- <?php
- namespace DesignPatterns\Creational\StaticFactory;
- class FormatString implements FormatterInterface
- {
- }
FormatNumber.php
- <?php
- namespace DesignPatterns\Creational\StaticFactory;
- class FormatNumber implements FormatterInterface
- {
- }
1.9.5. Test
Tests/StaticFactoryTest.php
- <?php
- namespace DesignPatterns\Creational\StaticFactory\Tests;
- use DesignPatterns\Creational\StaticFactory\StaticFactory;
- use PHPUnit\Framework\TestCase;
- class StaticFactoryTest extends TestCase
- {
- public function testCanCreateNumberFormatter()
- {
- $this->assertInstanceOf(
- 'DesignPatterns\Creational\StaticFactory\FormatNumber',
- StaticFactory::factory('number')
- );
- }
- public function testCanCreateStringFormatter()
- {
- $this->assertInstanceOf(
- 'DesignPatterns\Creational\StaticFactory\FormatString',
- StaticFactory::factory('string')
- );
- }
- /**
- * @expectedException \InvalidArgumentException
- */
- public function testException()
- {
- StaticFactory::factory('object');
- }
- }