W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
避免以標(biāo)準(zhǔn)方式(new Foo())創(chuàng)建對(duì)象的成本,而是創(chuàng)建一個(gè)原型(prototype)并克隆它。
BookPrototype.php
<?php declare(strict_types=1); namespace DesignPatterns\Creational\Prototype; abstract class BookPrototype { protected string $title; protected string $category; abstract public function __clone(); public function getTitle(): string { return $this->title; } public function setTitle(string $title): void { $this->title = $title; } }
BarBookPrototype.php
<?php declare(strict_types=1); namespace DesignPatterns\Creational\Prototype; class BarBookPrototype extends BookPrototype { protected string $category = 'Bar'; public function __clone() { } }
FooBookPrototype.php
<?php declare(strict_types=1); namespace DesignPatterns\Creational\Prototype; class FooBookPrototype extends BookPrototype { protected string $category = 'Foo'; public function __clone() { } }
Tests/PrototypeTest.php
<?php declare(strict_types=1); namespace DesignPatterns\Creational\Prototype\Tests; use DesignPatterns\Creational\Prototype\BarBookPrototype; use DesignPatterns\Creational\Prototype\FooBookPrototype; use PHPUnit\Framework\TestCase; class PrototypeTest extends TestCase { public function testCanGetFooBook() { $fooPrototype = new FooBookPrototype(); $barPrototype = new BarBookPrototype(); for ($i = 0; $i < 10; $i++) { $book = clone $fooPrototype; $book->setTitle('Foo Book No ' . $i); $this->assertInstanceOf(FooBookPrototype::class, $book); } for ($i = 0; $i < 5; $i++) { $book = clone $barPrototype; $book->setTitle('Bar Book No ' . $i); $this->assertInstanceOf(BarBookPrototype::class, $book); } } }
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: