mirror of
https://github.com/DesignPatternsPHP/DesignPatternsPHP.git
synced 2025-07-31 12:10:10 +02:00
improved Flyweight
This commit is contained in:
39
Structural/Flyweight/TextFactory.php
Normal file
39
Structural/Flyweight/TextFactory.php
Normal file
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace DesignPatterns\Structural\Flyweight;
|
||||
|
||||
/**
|
||||
* 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 $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);
|
||||
} else {
|
||||
return new Word($name);
|
||||
}
|
||||
}
|
||||
|
||||
public function count(): int
|
||||
{
|
||||
return count($this->charPool);
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user