目的
在初始化实例成本高,实例化率高,可用实例不足的情况下,对象池可以极大地提升性能。在创建对象(尤其是通过网络)时间花销不确定的情况下,通过对象池在可期时间内就可以获得所需的对象。
无论如何,对象池模式在需要耗时创建对象方面,例如创建数据库连接,套接字连接,线程和大型图形对象(比方字体或位图等),使用起来都是大有裨益的。在某些情况下,简单的对象池(无外部资源,只占内存)可能效率不高,甚至会有损性能。
UML 类图
代码
WorkerPool.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
<?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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
<?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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
<?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的资料请关注服务器之家其它相关文章!
原文链接:https://www.cnblogs.com/phpyu/p/13589787.html