与简单工厂比较而言,优先使用 简单工厂模式!
<?php
namespace DesignPatterns\Creational\StaticFactory;
final class StaticFactory
{
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');
}
}
<?php
namespace DesignPatterns\Creational\StaticFactory;
interface FormatterInterface
{
}
<?php
namespace DesignPatterns\Creational\StaticFactory;
class FormatString implements FormatterInterface
{
}
<?php
namespace DesignPatterns\Creational\StaticFactory;
class FormatNumber implements FormatterInterface
{
}
<?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')
);
}
public function testException()
{
StaticFactory::factory('object');
}
}
网友评论