PHP 簡單工廠模式

2022-05-05 11:25 更新

目的

SimpleFactory 是一個簡單的工廠模式。

它不同于靜態(tài)工廠,因為它不是靜態(tài)的。因此,您可以擁有多個工廠,可以有不同的參數(shù),可以進行子類化,也可以模擬。它總是比靜態(tài)工廠更受歡迎!

UML 圖

Alt SimpleFactory UML Diagram

代碼

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);
    }
}


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號