Last active
November 5, 2018 12:02
-
-
Save diloabininyeri/e21279288efd7b8a73d0cbed48eebb79 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Class Pool | |
* @author dılo sürücü <[email protected]> | |
* example pool design pattern | |
*/ | |
Class Pool | |
{ | |
private $free = [], $occupation = []; | |
/** | |
* @return mixed|Time | |
* | |
* | |
*/ | |
function get() | |
{ | |
if (count($this->free) == 0) { | |
$worker = new Time(); | |
} else { | |
$worker = array_pop($this->free); | |
} | |
$this->occupation[spl_object_hash($worker)] = $worker; | |
return $worker; | |
} | |
/** | |
* @param $worker | |
* | |
* | |
*/ | |
function dispos($worker) | |
{ | |
if (isset($this->occupation[spl_object_hash($worker)])) { | |
unset($this->occupation[spl_object_hash($worker)]); | |
$this->free[spl_object_hash($worker)] = $worker; | |
} | |
} | |
/** | |
* @return int | |
* | |
*/ | |
function count() | |
{ | |
return count($this->free); | |
} | |
} | |
/** | |
* Class Time | |
* | |
* | |
*/ | |
class Time | |
{ | |
/** | |
* @return DateTime | |
* | |
*/ | |
function getTime() | |
{ | |
return new DateTime(); | |
} | |
} | |
$pool = new Pool(); | |
$worker1 = $pool->get(); | |
$worker2 = $pool->get(); | |
$worker3 = $pool->get(); | |
/** | |
* | |
* dispos $workers | |
*/ | |
$pool->dispos($worker1); | |
$pool->dispos($worker2); | |
print_r($pool->count()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment