享元模式
享元模式是一种结构型设计模式, 它摒弃了在每个对象中保存所有数据的方式, 通过共享多个对象所共有的相同状态, 让你能在有限的内存容量中载入更多对象
类图
代码
<?php // 享元接口interface Shape{ public function draw(string $color): void;} // 具体享元类:圆形class Circle implements Shape{ private $radius; public function __construct(int $radius) { $this->radius = $radius; } public function draw(string $color): void { echo "Drawing a Circle with radius {$this->radius} and color {$color}\n"; }} class ShapeFactory{ private $circles = []; public function getCircle(int $radius): Circle { if (!isset($this->circles[$radius])) { $this->circles[$radius] = new Circle($radius); } return $this->circles[$radius]; } public function getCircleCount(): int { return count($this->circles); }} // 客户端代码$factory = new ShapeFactory(); $colors = ["Red", "Green", "Blue", "Yellow", "Black"]; for ($i = 0; $i < 10; $i++) { $radius = rand(1, 3); // 随机半径为 1 到 3 的圆 $circle = $factory->getCircle($radius); $color = $colors[array_rand($colors)]; $circle->draw($color);} echo "Total Circle objects created: " . $factory->getCircleCount() . "\n";
不使用享元模式
<?php // 不使用享元模式的具体类:圆形class CircleWithoutFlyweight{ private $radius; public function __construct(int $radius) { $this->radius = $radius; } public function draw(string $color): void { echo "Drawing a Circle with radius {$this->radius} and color {$color}\n"; }} // 客户端代码$colors = ["Red", "Green", "Blue", "Yellow", "Black"]; for ($i = 0; $i < 10; $i++) { $radius = rand(1, 3); // 随机半径为 1 到 3 的圆 $circle = new CircleWithoutFlyweight($radius); $color = $colors[array_rand($colors)]; $circle->draw($color);}