###模式定义 与简单工厂类似,该模式用于创建一组相关或依赖的对象,不同之处在于静态工厂模式使用一个静态方法来创建所有类型的对象,该静态方法通常是 factory 或 build。 ###UML类图  ###示例代码 StaticFactory.php ```php <?php namespace App\Sheji\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 <?php namespace App\Sheji\StaticFactory; /** * FormatterInterface接口 */ interface FormatterInterface { } ``` FormatString.php ```php <?php namespace App\Sheji\StaticFactory; /** * FormatNumber类 */ class FormatNumber implements FormatterInterface { } ``` ###测试代码 Tests/StaticFactoryTest.php ```php <?php namespace App\Sheji\StaticFactory\Tests; use App\Sheji\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('App\Sheji\StaticFactory\FormatterInterface', $obj); } /** * @expectedException InvalidArgumentException */ public function testException() { StaticFactory::factory(""); } } ``` ###总结 通常我们会使用new关键字调用类的构造方法来创建一个对象,静态工厂模式相对于传统的创建对象的方式有以下优点 - 可以更加富有语义的创建实例:当一个类的构造方法有非常多的参数或被重载过很多次的话,因为JAVA对构造方法命名的规定(与类名相同),我们必须编写多个命名相同但实际不同的构造函数,在创建对象时很难区分我们应该调用哪个构造方法。 - 当一个类的对象会被频繁使用,且没有必要在每次使用时都生成新的对象时,我们会考虑使用单例模式。单例模式大多是由静态工厂实现的,我们可以在工厂内部控制新生成实例或返回已有实例。