简单工厂模式

目的

这是一个简单的工厂模式。

它不同于静态工厂模式,因为它不是静态的。因此,你可以有多个工厂,这些工厂有不同的参数,你可以把它作为子类,也可以模拟它。它总是应该优先于静态工厂模式!

UML 类图

简单工厂模式类图

代码

SimpleFactory.php

1
2
3
4
5
6
7
8
9
10
11
<?php declare(strict_types = 1);

namespace DesignPatterns\Creational\SimpleFactory;

class SimpleFactory
{
public function createBicycle(): Bicycle
{
return new Bicycle();
}
}

Bicycle.php

1
2
3
4
5
6
7
8
9
10
<?php declare(strict_types = 1);

namespace DesignPatterns\Creational\SimpleFactory;

class Bicycle
{
public function driveTo(string $destination)
{
}
}

使用

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

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php declare(strict_types = 1);

namespace DesignPatterns\Creational\SimpleFactory\Tests;

use DesignPatterns\Creational\SimpleFactory\Bicycle;
use DesignPatterns\Creational\SimpleFactory\SimpleFactory;
use PHPUnit\Framework\TestCase;

class SimpleFactoryTest extends TestCase
{
public function testCanCreateBicycle()
{
$bicycle = (new SimpleFactory())->createBicycle();
$this->assertInstanceOf(Bicycle::class, $bicycle);
}
}