享元模式(对象池模式)

我在网上也看到了一些实现,感觉都不是太满意,所以按照我的理解写了一份

 

  1 <?php
  2 
  3 /**
  4  * 具体的需要缓存的对象, 因new的代价太高昂, 所以做一个缓存
  5  */
  6 class Worker
  7 {
  8     public function __construct()
  9     {
 10         //做一些代价高昂的事情,比如创建线程
 11     }
 12 
 13     public function run($class, $functionName)
 14     {
 15         //对$class做一些事情
 16         //这个$class, 是想使用Worker的类
 17 
 18         echo "<br/>我正在处理: {$class},  它的数据类型是:".gettype($class); //for test
 19 
 20         call_user_func($functionName, $this);
 21     }
 22 }
 23 
 24 class Pool
 25 {
 26     private $_pool = [];            //对象池
 27     private $_maxNum;               //对象池中的最大对象数目
 28     private $_waitingQueue = [];   //等待队列
 29 
 30     function __construct($maxNum)
 31     {
 32         $this->_maxNum = $maxNum;
 33 
 34         //初始化对象池
 35         for ($i=0; $i<$this->_maxNum; $i++) {
 36             $worker = new Worker();
 37             $this->_pool[] = $worker;
 38         }
 39     }
 40 
 41     /**
 42      * 从对象池中取出
 43      * @param $class  Object  想使用Worker的对象
 44      */
 45     public function get($class)
 46     {
 47         if (count($this->_pool)) {
 48             $this->callWorker($class);
 49         } else {
 50             $this->pushToWaitingQueue($class);
 51         }
 52     }
 53 
 54     /**
 55      * 我已经使用好啦,还给你啦
 56      * @param $worker
 57      */
 58     public function done($worker)
 59     {
 60         echo "<br/>哈哈,我胡汉三又回来啦!";   //for test
 61 
 62 
 63         $this->_pool[] = $worker;
 64 
 65         if (count($this->_waitingQueue) > 0) {
 66             $class = $this->popFromWaitingQueue();
 67             $this->callWorker($class);
 68         }
 69     }
 70 
 71 
 72 
 73 
 74 
 75     private function callWorker($class)
 76     {
 77         $worker = array_pop($this->_pool);
 78         $worker->run($class, [$this, 'done']);
 79     }
 80 
 81     private function pushToWaitingQueue($class)
 82     {
 83         $this->_waitingQueue[] = $class;
 84     }
 85 
 86     private function popFromWaitingQueue()
 87     {
 88         return array_pop($this->_waitingQueue);
 89     }
 90 }
 91 
 92 
 93 
 94 $pool = new Pool(3);
 95 
 96 $c1 = 3;
 97 $pool->get($c1);
 98 
 99 $c2 = 'sdfsdf';
100 $pool->get($c2);
View Code
原文地址:https://www.cnblogs.com/hangtt/p/6258804.html