zoukankan      html  css  js  c++  java
  • [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();
  • 相关阅读:
    股票F10
    什么是盘口?
    CompletionPort
    WSAEvent
    SO_KEEPALIVE选项
    SO_LINGER
    shutdown和close的区别
    TIME_WAIT和CLOSE_WAIT状态区别
    什么是2MSL
    WSAStartup function
  • 原文地址:https://www.cnblogs.com/taoshihan/p/13809746.html
Copyright © 2011-2022 走看看