SimpleFactory 是一個簡單的工廠模式。
它不同于靜態(tài)工廠,因為它不是靜態(tài)的。因此,您可以擁有多個工廠,可以有不同的參數(shù),可以進行子類化,也可以模擬。它總是比靜態(tài)工廠更受歡迎!
SimpleFactory.php
<?php
declare(strict_types=1);
namespace DesignPatterns\Creational\SimpleFactory;
class SimpleFactory
{
public function createBicycle(): Bicycle
{
return new Bicycle();
}
}
Bicycle.php
<?php
declare(strict_types=1);
namespace DesignPatterns\Creational\SimpleFactory;
class Bicycle
{
public function driveTo(string $destination)
{
}
}
$factory = new SimpleFactory();
$bicycle = $factory->createBicycle();
$bicycle->driveTo('Paris');
Tests/SimpleFactoryTest.php
<?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);
}
}
更多建議: