淺談PHP設計模式之對象池模式Pool

目的

在初始化實例成本高,實例化率高,可用實例不足的情況下,對象池可以極大地提升性能。在創建對象(尤其是通過網絡)時間花銷不確定的情況下,通過對象池在可期時間內就可以獲得所需的對象。

無論如何,對象池模式在需要耗時創建對象方面,例如創建數據庫連接,套接字連接,線程和大型圖形對象(比方字體或位圖等),使用起來都是大有裨益的。在某些情況下,簡單的對象池(無外部資源,隻占內存)可能效率不高,甚至會有損性能。

UML 類圖

代碼

WorkerPool.php

<?php

namespace DesignPatterns\Creational\Pool;

class WorkerPool implements \Countable
{
    /**
    * @var StringReverseWorker[]
    */
    private $occupiedWorkers = [];

    /**
    * @var StringReverseWorker[]
    */
    private $freeWorkers = [];

    public function get(): StringReverseWorker
    {
        if (count($this->freeWorkers) == 0) {
            $worker = new StringReverseWorker();
        } else {
            $worker = array_pop($this->freeWorkers);
        }

        $this->occupiedWorkers[spl_object_hash($worker)] = $worker;

        return $worker;
    }

    public function dispose(StringReverseWorker $worker)
    {
        $key = spl_object_hash($worker);

        if (isset($this->occupiedWorkers[$key])) {
            unset($this->occupiedWorkers[$key]);
            $this->freeWorkers[$key] = $worker;
        }
    }

    public function count(): int
    {
        return count($this->occupiedWorkers) + count($this->freeWorkers);
    }
}

StringReverseWorker.php

<?php

namespace DesignPatterns\Creational\Pool;

class StringReverseWorker
{
    /**
    * @var \DateTime
    */
    private $createdAt;

    public function __construct()
    {
        $this->createdAt = new \DateTime();
    }

    public function run(string $text)
    {
        return strrev($text);
    }
}

測試

Tests/PoolTest.php

<?php

namespace DesignPatterns\Creational\Pool\Tests;

use DesignPatterns\Creational\Pool\WorkerPool;
use PHPUnit\Framework\TestCase;

class PoolTest extends TestCase
{
    public function testCanGetNewInstancesWithGet()
    {
        $pool = new WorkerPool();
        $worker1 = $pool->get();
        $worker2 = $pool->get();

        $this->assertCount(2, $pool);
        $this->assertNotSame($worker1, $worker2);
    }

    public function testCanGetSameInstanceTwiceWhenDisposingItFirst()
    {
        $pool = new WorkerPool();
        $worker1 = $pool->get();
        $pool->dispose($worker1);
        $worker2 = $pool->get();

        $this->assertCount(1, $pool);
        $this->assertSame($worker1, $worker2);
    }
}

以上就是淺談PHP設計模式之對象池模式Pool的詳細內容,更多關於PHP設計模式之對象池模式Pool的資料請關註WalkonNet其它相關文章!

推薦閱讀: