您的位置 首页 php

9 PHP 设计模式系列「静态工厂模式(Static Factory)」

1、模式定义

与简单工厂类似,该模式用于创建一组相关或依赖的对象,不同之处在于静态 工厂模式 使用一个 静态方法 来创建所有类型的对象,该静态方法通常是 factory 或 build。

2、UML类图

3、示例代码

static Factory.php

<?php
namespace DesignPatterns\Creational\StaticFactory;
class StaticFactory
{
 /**
 * 通过传入参数创建相应对象实例
 *
 * @param string $type
 *
 * @static
 *
 * @ throws  \InvalidArgumentException
 * @return FormatterInterface
 */
 public static function factory($type)
 {
 $className = __NAMESPACE__ . '\Format' . ucfirst($type);
 if (!class_exists($className)) {
 throw new \InvalidArgumentException('Missing format class.');
 }
 return new $className();
 }
}
 

FormatterInterface.php

<?php
namespace DesignPatterns\Creational\StaticFactory;
/**
 * FormatterInterface接口
 */
interface FormatterInterface
{
}
 

FormatString.php

<?php
namespace DesignPatterns\Creational\StaticFactory;
/**
 * FormatNumber类
 */
class FormatNumber implements FormatterInterface
{
}
 

4、测试代码

Tests/StaticFactoryTest.php

<?php
namespace DesignPatterns\Creational\StaticFactory\Tests;
use DesignPatterns\Creational\StaticFactory\StaticFactory;
/**
 * 测试静态工厂模式
 *
 */
class StaticFactoryTest extends \PHPUnit_Framework_TestCase
{
 public function getTypeList()
 {
 return array(
 array('string'),
 array('number')
 );
 }
 /**
 * @dataProvider getTypeList
 */
 public function testCreation($type)
 {
 $obj = StaticFactory::factory($type);
 $this->assertInstanceOf('DesignPatterns\Creational\StaticFactory\FormatterInterface', $obj);
 }
 /**
 * @expectedException InvalidArgumentException
 */
 public function testException()
 {
 StaticFactory::factory("");
 }
}
 

文章来源:智云一二三科技

文章标题:9 PHP 设计模式系列「静态工厂模式(Static Factory)」

文章地址:https://www.zhihuclub.com/149129.shtml

关于作者: 智云科技

热门文章

网站地图