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

2019-04-22 17:38 By "Powerless" 2621 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学院 ,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责。
如有侵权行为,请联系我们,我们会及时删除。

评 论

View in WeChat

Others Discussion

  • 分布式服务限流
    Posted on 2020-02-07 18:57
  • 有状态服务VS无状态服务
    Posted on 2020-02-07 18:18
  • 企业级PAAS云平台几个关键问题和挑战
    Posted on 2019-06-12 18:33
  • MySQL 单库后期分库策略
    Posted on 2019-08-19 14:31
  • Redis七大经典问题
    Posted on 2021-05-27 11:14
  • 关于HTTPS的五大误区
    Posted on 2020-02-02 01:10
  • PHP实现精确发布时间
    Posted on 2018-12-06 21:00
  • 为什么要测量尾部延迟
    Posted on 2020-09-18 10:34

1.354252s