W3Cschool
恭喜您成為首批注冊用戶
獲得88經驗值獎勵
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);
}
}
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: