PHP设计模式 - 静态工厂模式

2019-04-22 17:38 By "Powerless" 2740 0 1

【一】模式定义

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


【二】UML类图

image.png


【三】示例代码

StaticFactory.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
{
}


【四】测试代码

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("");
    }
}


注:本文转载自 Laravel学院 ,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责。
如有侵权行为,请联系我们,我们会及时删除。

评 论

Others Discussion

  • 浏览器访问网站经历的步骤-Html
    Posted on 2018-11-28 18:48
  • BASE原则
    Posted on 2020-12-17 16:42
  • 程序员年中考试题-段子版
    Posted on 2021-06-23 15:57
  • 前端知识体系精简-Css
    Posted on 2018-03-28 18:34
  • Mysql联合索引的最左前缀匹配原则
    Posted on 2018-08-25 15:00
  • 2016年云计算热词
    Posted on 2019-06-12 17:53
  • PHP没你想的那么差
    Posted on 2021-12-17 15:40
  • 分布式架构之「 数据分布」
    Posted on 2019-11-14 10:00