Creational --- Static Factory

Purpose:

Similiar to the AbstractFactory, this pattern is used to create series of related or dependent objects. The difference between this and abstract factory pattern is that the static factory pattern uses just one static method to create all types of objects it can create. It is usually named factory or build.

StaticFactory.php

<?php 

namespace DesignPatterns\Creational\StaticFactory;

/**
 * Note1: Remember, static means global state which is evil because it can't be mocked for tests
 * Note2: Cannot be subclassed or mock-upped or have multiple different instances.
 */

final class StaticFactory
{
    /**
        * @param string $type
        *
        * @return FormatterInterface
    */
    public static function factory(string $type): FormatterInterface
    {
        if ($type == 'number') {
            return new FormatNumber();
        }

        if ($type == 'string') {
            return new FormatString();
        }

        throw new \InvalidArgumentException("Unknow format given");
    }
}

?>

  

FormatterInterface.php

<?php

namespace DesignPatterns\Creational\StaticFactory;

interface FormatterInterface
{
}

  

FormatString.php

<?php 

namespace DesignPattern\Creational\StaticFactory;

class FormatString implements FormatterInterface
{
    
}
?>

  

FormatNumber.php

<?php 

namespace DesignPatterns\Creational\StaticFactory;

class FormatNumber implements FormatterInterface
{
    
}
?>

  

Tests/StaticFactoryTest.php

<?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')
            );
        }

        /**
         * @expectedException \InvalidArgumentException
         */
        public function testException()
        {
            StaticFactory::factory('object');
        }
    }
}

?>

  

转载于:https://www.cnblogs.com/victorchen/p/10832362.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值