[PHP] 对象池模式-创建型设计模式

最重要的特征是,有两个数组存对象,忙的数组和闲的数组.
当使用对象后,不是立即销毁对象,而是放回池子闲的数组里面,下次使用直接拿,拿到后放到忙的数组里.当拿不到的时候就再创建新

 

class WorkerPool
{
    /**
     * @var 忙的数组
     */
    private array $occupiedWorkers = [];

    /**
     * @var 清闲的数组
     */
    private array $freeWorkers = [];
    //拿对象
    public function get(): MyObj
    {
        if (count($this->freeWorkers) == 0) {
            $worker = new MyObj();
        } else {
            $worker = array_pop($this->freeWorkers);
        }
        $this->occupiedWorkers[spl_object_hash($worker)] = $worker;
        return $worker;
    }
    //放回对象
    public function dispose(MyObj $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);
    }
}


$pool = new WorkerPool();
$worker1 = $pool->get();
$pool->dispose($worker1);
$worker2 = $pool->get();

 

posted @ 2020-10-13 16:43  陶士涵  阅读(10)  评论(0编辑  收藏