@blog.justoneplanet.info

日々勉強

Flyweight Pattern

同じものは一度しか作らない。

■コード

Item.php

class Item {
    private $code;
    private $name;
    private $price;
    public function __construct($code, $name, $price) {
        $this->code = $code;
        $this->name = $name;
        $this->price = $price;
    }
}

ItemFactory.php

class ItemFactory {
    private $pool;
    private static $instance = null;
    private function __construct($filename) {
        $this->buildPool($filename);
    }
    public static function getInstance($filename) {
        if(!is_null(self::$instance)) {
            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;
        }
    }
    public function buildPool($filename) {
        $this->pool = array();
        $fh = fopen($filename, 'r');
        while($buffer = fgets($fp, 4096)) {
            list($itemCode, $itemName, $price) = split("\t", $buffer);
            $this->pool[$itemCode] = new Item($itemCode, $itemName, $price);
        }
        fclose($fh);
    }
    public final __clone() {
        throw new RuntimeException();
    }
}

■クライアントコード

$factory = ItemFactory::getInstance('list.dat');
$factory->getItem(123);// 何度コールしても同じインスタンスが返るはず
$factory->getItem(456);//
$factory->getItem(789);//

Singletonをまとめた感じだ。

コメントはまだありません»

No comments yet.

RSS feed for comments on this post.TrackBack URL

Leave a comment