1.6. 简单工厂
1.6.1. 目的
SimpleFactory 是一个简单的工厂模式。
它不同于静态工厂,因为它不是静态的。因此,您可以拥有多个工厂,可以有不同的参数,可以进行子类化,也可以模拟。它总是比静态工厂更受欢迎!
1.6.2. UML 图

1.6.3. 代码
你可以在 GitHub 上找到这些代码
SimpleFactory.php
1<?php
2
3declare(strict_types=1);
4
5namespace DesignPatterns\Creational\SimpleFactory;
6
7class SimpleFactory
8{
9 public function createBicycle(): Bicycle
10 {
11 return new Bicycle();
12 }
13}
Bicycle.php
1<?php
2
3declare(strict_types=1);
4
5namespace DesignPatterns\Creational\SimpleFactory;
6
7class Bicycle
8{
9 public function driveTo(string $destination)
10 {
11 }
12}
1.6.4. Usage
1 $factory = new SimpleFactory();
2 $bicycle = $factory->createBicycle();
3 $bicycle->driveTo('Paris');
1.6.5. 测试
Tests/SimpleFactoryTest.php
1<?php
2
3declare(strict_types=1);
4
5namespace DesignPatterns\Creational\SimpleFactory\Tests;
6
7use DesignPatterns\Creational\SimpleFactory\Bicycle;
8use DesignPatterns\Creational\SimpleFactory\SimpleFactory;
9use PHPUnit\Framework\TestCase;
10
11class SimpleFactoryTest extends TestCase
12{
13 public function testCanCreateBicycle()
14 {
15 $bicycle = (new SimpleFactory())->createBicycle();
16 $this->assertInstanceOf(Bicycle::class, $bicycle);
17 }
18}