forked from DesignPatternsPHP/DesignPatternsPHP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TextFactory.php
41 lines (33 loc) · 863 Bytes
/
TextFactory.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
<?php
declare(strict_types=1);
namespace DesignPatterns\Structural\Flyweight;
use Countable;
/**
* A factory manages shared flyweights. Clients should not instantiate them directly,
* but let the factory take care of returning existing objects or creating new ones.
*/
class TextFactory implements Countable
{
/**
* @var Text[]
*/
private array $charPool = [];
public function get(string $name): Text
{
if (!isset($this->charPool[$name])) {
$this->charPool[$name] = $this->create($name);
}
return $this->charPool[$name];
}
private function create(string $name): Text
{
if (strlen($name) == 1) {
return new Character($name);
}
return new Word($name);
}
public function count(): int
{
return count($this->charPool);
}
}