Created
August 21, 2018 02:39
-
-
Save bz0/968e51670059af770baff4bab1e20674 to your computer and use it in GitHub Desktop.
GoF Proxyパターン
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 $id; | |
private $name; | |
public function __construct($id, $name){ | |
$this->id = $id; | |
$this->name = $name; | |
} | |
public function getId(){ | |
return $this->id; | |
} | |
public function getName(){ | |
return $this->name; | |
} | |
} | |
interface ItemDao{ | |
public function findById($item_id); | |
} | |
class DbItemDao implements ItemDao{ | |
public function findById($item_id){ | |
$fp = fopen('item_data.txt', 'r'); | |
$dummy = fgets($fp, 4096); | |
$item = null; | |
while($buffer = fgets($fp, 4096)){ | |
$id = trim(substr($buffer, 0, 10)); | |
$name = trim(substr($buffer, 10)); | |
if ($item_id === (int)$id){ | |
$item = new Item($id, $name); | |
break; | |
} | |
} | |
fclose($fp); | |
return $item; | |
} | |
} | |
class MockItemDao implements ItemDao{ | |
public function findById($item_id){ | |
$item = new Item($item_id, 'ダミー商品'); | |
return $item; | |
} | |
} | |
class ItemDaoProxy{ | |
private $dao; | |
private $cache; | |
public function __construct(ItemDao $dao){ | |
$this->dao = $dao; | |
$this->cache = array(); | |
} | |
public function findById($item_id){ | |
if (array_key_exists($item_id, $this->cache)){ | |
echo '<font color="#dd0000">Proxyで保持しているキャッシュからデータを返します</font><br>'; | |
return $this->cache[$item_id]; | |
} | |
$this->cache[$item_id] = $this->dao->findById($item_id); | |
return $this->cache[$item_id]; | |
} | |
} | |
$dao = new MockItemDao(); | |
$dao2 = new DbItemDao(); | |
$proxy = new ItemDaoProxy($dao); | |
$item = $proxy->findById(1); | |
echo "商品ID=" . $item->getId() . " 商品名=" . $item->getName() . "<br>"; | |
$item = $proxy->findById(1); | |
echo "商品ID=" . $item->getId() . " 商品名=" . $item->getName() . "<br>"; | |
$proxy = new ItemDaoProxy($dao2); | |
$item = $proxy->findById(2); | |
echo "商品ID=" . $item->getId() . " 商品名=" . $item->getName() . "<br>"; | |
$item = $proxy->findById(2); | |
echo "商品ID=" . $item->getId() . " 商品名=" . $item->getName() . "<br>"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment