简单工厂模式(Simple Factory)

目的

简单工厂模式是一个精简版的工厂模式。

它与静态工厂模式最大的区别是它不是『静态』的。因为非静态,所以你可以拥有多个不同参数的工厂,你可以为其创建子类。甚至可以模拟(Mock)他,这对编写可测试的代码来讲至关重要。 这也是它比静态工厂模式受欢迎的原因!

UML 图

tsAa4MVih0.png

代码

你可以在 GitHub 查看这段代码。

SimpleFactory.php

  1. <?php
  2. namespace DesignPatterns\Creational\SimpleFactory;
  3. class SimpleFactory
  4. {
  5. public function createBicycle(): Bicycle
  6. {
  7. return new Bicycle();
  8. }
  9. }

Bicycle.php

  1. <?php
  2. namespace DesignPatterns\Creational\SimpleFactory;
  3. class Bicycle
  4. {
  5. public function driveTo(string $destination)
  6. {
  7. return $destination;
  8. }
  9. }

用法

  1. $factory = new SimpleFactory();
  2. $bicycle = $factory->createBicycle();
  3. $bicycle->driveTo('Paris');

测试

Tests/SimpleFactoryTest.php

  1. <?php
  2. namespace DesignPatterns\Creational\SimpleFactory\Tests;
  3. use DesignPatterns\Creational\SimpleFactory\Bicycle;
  4. use DesignPatterns\Creational\SimpleFactory\SimpleFactory;
  5. use PHPUnit\Framework\TestCase;
  6. class SimpleFactoryTest extends TestCase
  7. {
  8. public function testCanCreateBicycle()
  9. {
  10. $bicycle = (new SimpleFactory())->createBicycle();
  11. $this->assertInstanceOf(Bicycle::class, $bicycle);
  12. }
  13. }