目的

与抽象工厂模式类似,此模式用于创建一系列相关或相互依赖的对象。【静态工厂模式】与【抽象工厂模式】的区别在于,只使用一个静态方法来创建所有类型对象,此方法通常被命名为 factorybuild

例子

  • Zend Framework: Zend_Cache_Backend_Frontend 使用工厂方法创建缓存后端或前端

UML 图

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
StaticFactory.php
<?php
namespace DesignPatterns\Creational\StaticFactory;
/**
* 注意点1:记住,静态意味着全局状态,因为它不能被模式进行测试,所以它是有弊端的。
* 注意点2:不能被分类或模拟或有多个不同的实例
*/
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('Unkonwn format given');
}
}

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

}

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

}

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

}

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Tests/StaticFactoryTest.php
<?php
namespace DesignPatterns\Creational\StaticFactory\Tests;
user DesignPatterns\Creational\StaticFactory\StaticFactory;
user 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');
}
}