• 追加された行はこの色です。
  • 削除された行はこの色です。
* Flyweightパターン [#nbf11d15]

 <?php
 class Foo {
     private $val = 0;
     private $pool = array();
     public function getVal($key) {
     public function getValue($key) {
         if (!isset($this->pool[$key])) {
            $this->pool[$key] = $this->create();
         }
         return $this->pool[$key];
     }
     private function create() {
         return ++$this->val;
         return rand(0,1000);
     }
     public function clear($key) {
         unset($this->pool[$key]);
     }
 }
 
 $f = new Foo;
 print $f->getVal(1) . "\n";  # 1
 print $f->getVal(1) . "\n";  # 1
 print $f->getVal(2) . "\n";  # 2
 print $f->getVal(1) . "\n";  # 1
 print $f->getValue(1) . "\n"; # 328
 print $f->getValue(1) . "\n"; # 328
 print $f->getValue(2) . "\n"; # 912
 print $f->getValue(1) . "\n"; # 328
 $f->clear(1);
 print $f->getVal(1) . "\n";  # 3
 print $f->getValue(1) . "\n"; # 381

** キャッシュ処理の実装を独立させて [#s6006c20]

 <?php
 class FlyweightImplement {
     public function create() {
         return rand(0,1000);
     }
     public function clear($key) {
         unset($this->pool[$key]);
     }
 }
 interface FlyweightInterface {
     public function create();
     public function clear($key);
 }
 class Foo implements FlyweightInterface {
     private $flyweightImplement = null;
     private $pool = array();
     public function __construct() {
         $this->flyweightImplement = new FlyweightImplement;
     }
     public function getValue($key) {
         if (!isset($this->pool[$key])) {
            $this->pool[$key] = $this->create();
         }
         return $this->pool[$key];
     }
     public function create() {
         return $this->flyweightImplement->create();
     }
     public function clear($key) {
         return $this->flyweightImplement->clear($key);
     }
 }


トップ   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS