-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathTurnipsPool.php
70 lines (59 loc) · 1.17 KB
/
TurnipsPool.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<?php
namespace DesignPatterns\Creational\PoolPattern;
use Countable;
/**
* Class TurnipsPool.
*/
class TurnipsPool implements Countable
{
/**
* @var Turnips[]
*/
protected $pool = [];
/**
* @var int
*/
protected $total = 0;
/**
* @return Turnips
*/
public function get(string $key = null): Turnips
{
if (isset($key)) {
$turnips = $this->pool[$key];
unset($this->pool[$key]);
} else {
$turnips = array_pop($this->pool);
}
$this->total -= $turnips->calculatePrice();
return $turnips;
}
/**
* 把大頭菜塞到池子裡
*
* @param Turnips $turnips
*
* @return string
*/
public function set(Turnips $turnips): string
{
$key = spl_object_hash($turnips);
$this->total += $turnips->calculatePrice();
$this->pool[$key] = $turnips;
return $key;
}
/**
* @return int
*/
public function total(): int
{
return $this->total;
}
/**
* @return int
*/
public function count(): int
{
return count($this->pool);
}
}