目的
在初始化實(shí)例成本高,實(shí)例化率高,可用實(shí)例不足的情況下,對(duì)象池可以極大地提升性能。在創(chuàng)建對(duì)象(尤其是通過網(wǎng)絡(luò))時(shí)間花銷不確定的情況下,通過對(duì)象池在可期時(shí)間內(nèi)就可以獲得所需的對(duì)象。
無論如何,對(duì)象池模式在需要耗時(shí)創(chuàng)建對(duì)象方面,例如創(chuàng)建數(shù)據(jù)庫(kù)連接,套接字連接,線程和大型圖形對(duì)象(比方字體或位圖等),使用起來都是大有裨益的。在某些情況下,簡(jiǎn)單的對(duì)象池(無外部資源,只占內(nèi)存)可能效率不高,甚至?xí)袚p性能。
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);
}
}
測(cè)試
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設(shè)計(jì)模式之對(duì)象池模式Pool的詳細(xì)內(nèi)容,更多關(guān)于PHP設(shè)計(jì)模式之對(duì)象池模式Pool的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
您可能感興趣的文章:- PHP設(shè)計(jì)模式(觀察者模式)
- 淺談PHP設(shè)計(jì)模式之門面模式Facade
- 詳解PHP設(shè)計(jì)模式之依賴注入模式
- PHP設(shè)計(jì)模式之迭代器模式的使用
- 詳解PHP八大設(shè)計(jì)模式
- PHP設(shè)計(jì)模式之原型模式示例詳解
- PHP設(shè)計(jì)模式之命令模式示例詳解
- PHP八大設(shè)計(jì)模式案例詳解