PHP设计模式 PHP 原型模式

2024-02-26 开发教程 PHP设计模式 匿名 0

目的

避免以标准方式(new Foo())创建对象的成本,而是创建一个原型(prototype)并克隆它。

例子

  • 大量数据(例如:通过 ORM 在数据库中创建百万行数据。)

UML 图

代码

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