Flyweight パターン | デザインパターン
2022年9年25日
デザインパターン
Flyweight
PHP

オライリージャパンによる Head First シリーズ デザインパターン(第2版)第14章 Flyweight パターンを、 PHPで書き直してみようという試みです。
Tree.php
namespace Flyweight;
class Tree {
public static function display(int $x, int $y, int $age) : void {
echo 'x座標:' . $x . "\n";
echo 'y座標:' . $y . "\n";
echo '樹齢:' . $age . "\n\n";
}
}
TreeManager.php
namespace Flyweight;
use Flyweight\Tree;
class TreeManager {
private array $treeArray = [];
public function __construct() {
for ($i = 0; $i < 10; $i++) {
for ($j = 0; $j < 10; $j++) {
$this->treeArray[] = [$i, $j, rand(1,100)];
}
}
}
public function displayTrees() : void {
for ($i = 0; $i < count($this->treeArray); $i++) {
Tree::display($this->treeArray[$i][0], $this->treeArray[$i][1], $this->treeArray[$i][2]);
}
}
}
index.php
use Flyweight\Tree; use Flyweight\TreeManager; $treeManager = new TreeManager(); $trees = $treeManager->displayTrees();
出力結果
x座標:0 y座標:0 樹齢:3 x座標:0 y座標:1 樹齢:87 x座標:0 y座標:2 樹齢:60 ・ ・ ・ x座標:9 y座標:7 樹齢:78 x座標:9 y座標:8 樹齢:28 x座標:9 y座標:9 樹齢:53