Created
July 30, 2018 11:52
-
-
Save bz0/bc3b1c9f9920f5d66b1ddbc16a9f2eb5 to your computer and use it in GitHub Desktop.
GoF Flyweightパターン
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Item { | |
private $code; | |
private $name; | |
private $price; | |
public function __construct($code, $name, $price){ | |
$this->code = $code; | |
$this->name = $name; | |
$this->price = $price; | |
} | |
public function getCode(){ | |
return $this->code; | |
} | |
public function getName(){ | |
return $this->name; | |
} | |
public function getPrice(){ | |
return $this->price; | |
} | |
} | |
class ItemFactory{ | |
private $pool; | |
private static $instance = null; | |
private function __construct($filename){ | |
//②buildPoolメソッド実行 | |
$this->buildPool($filename); | |
} | |
public static function getInstance($filename){ | |
if (is_null(self::$instance)){ | |
//①ItemFactoryをインスタンス化 | |
self::$instance = new ItemFactory($filename); | |
} | |
return self::$instance; | |
} | |
public function getItem($code){ | |
if (array_key_exists($code, $this->pool)){ | |
return $this->pool[$code]; | |
}else{ | |
return null; | |
} | |
} | |
private function buildPool($filename){ | |
$this->pool = array(); | |
//ファイルを開いて行ごとにItemインスタンスを生成し、poolプロパティにセットする | |
$fp = fopen($filename, 'r'); | |
while($buffer = fgets($fp, 4096)){ | |
var_dump(explode("\t", $buffer)); | |
list($item_code, $item_name, $price) = explode("\t", $buffer); | |
$this->pool[$item_code] = new Item($item_code, $item_name, $price); | |
} | |
fclose($fp); | |
} | |
public final function __clone(){ | |
throw new RuntimeException('Clone is not allowed against ' . get_class($this)); | |
} | |
} | |
function dumpData($items){ | |
echo "<dl>"; | |
foreach($items as $item){ | |
echo "<dt>" . $item->getName() . "</dt>"; | |
echo "<dd>" . $item->getCode() . "</dd>"; | |
echo "<dd>" . $item->getPrice() . "</dd>"; | |
} | |
echo "</dl>"; | |
} | |
$factory = ItemFactory::getInstance('data.txt'); | |
$items = array(); | |
$items[] = $factory->getItem('ABC0001'); | |
$items[] = $factory->getItem('ABC0002'); | |
$items[] = $factory->getItem('ABC0003'); | |
dumpData($items); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment