Development Blog

Collection of development articles I've put together...
Return to articles

Prototype Pattern

To avoid the cost of creating objects the standard way (new Foo()) and instead create a prototype and clone it.
0
Likes
2 years ago
Design Patterns: Creational
Purpose

To avoid the cost of creating objects the standard way (new Foo()) and instead create a prototype and clone it.

Examples

Large amounts of data (e.g. create 1,000,000 rows in a database at once via a ORM).

UML


Code

BookPrototype


namespace DesignPatterns\Creational\Prototype;

abstract class BookPrototype
{
    protected string $title;
    protected string $category;

    abstract public function __clone();

    final public function getTitle(): string
    {
        return $this->title;
    }

    final public function setTitle(string $title): void
    {
        $this->title = $title;
    }
}

FooBookPrototype


namespace DesignPatterns\Creational\Prototype;

class FooBookPrototype extends BookPrototype
{
    protected string $category = 'Foo';

    public function __clone()
    {
    }
}

BarBookPrototype


namespace DesignPatterns\Creational\Prototype;

class BarBookPrototype extends BookPrototype
{
    protected string $category = 'Bar';

    public function __clone()
    {
    }
}

Tests


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