前言

昨天看的是原型模式,大概意思就是,创建一个原型,然后直接克隆,这种方式比较节省开销

目的

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

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

UML 图

代码

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

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

}
}

用法

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
Test/SimpleFactoryTest.php
<?php
namespace DesignPatterns\Creational\SimpleFactory\Tests;
use DesignPatterns\Creational\SimpleFactoy\Bicycle;
use DesignPatterns\Creational\SimpleFactory\SimpleFactory;
use PHPUnit\Framework\TesCase;

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

}