php工厂模式简单代码(9PHP设计模式系列)
php工厂模式简单代码(9PHP设计模式系列)<?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 ge
1、模式定义与简单工厂类似,该模式用于创建一组相关或依赖的对象,不同之处在于静态工厂模式使用一个静态方法来创建所有类型的对象,该静态方法通常是 factory 或 build。
2、UML类图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 { }
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(""); } }