@blog.justoneplanet.info

日々勉強

Abstract Factory Pattern

■コード

DaoFactory.php

interface DaoFactory {
    public function createItemDao();
    public function createOrderDao();
}

DbFactory.php

class DbFactory implements DaoFactory {
    public function createItemDao() {
        return new DbItemDao();
    }
    public function createOrderDao() {
        return new DbOrderDao($this->createItemDao());
    }
}

MockFactory.php

class MockFactory implements DaoFactory {
    public function createItemDao() {
        return new MockItemDao();
    }
    public function createOrderDao() {
        return new MockOrderDao();
    }
}

ItemDao.php

interface ItemDao {
    public function findById($itemId);
}

OrderDao.php

interface OrderDao {
    public function findById($orderId);
}

DbItemDao.php

class DbItemDao implements ItemDao {
    public function findById($itemId) {
        // DBから$itemIdのものを取得して返す
    }
}
MockItemDao.php
class MockItemDao implements Item Dao {
    public function findById($itemId) {
        return new Item(7, "dummy");
    }
}

DbOrderDao.php

class DbOrderDao {
    public function findById($orderId) {
        // DBから$orderIdのものを取得して返す
    }
}
MockOrderDao.php
class MockOrderDao implements OrderDao {
    public function findById($orderId) {
        $order = new Order(123);
        $order->addItem(new Item(7, "dummy1"))->addItem(new Item(11, "dummy2"))->addItem(new Item(13, "dummy3"));
        return $order;
    }
}

Item.php

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

Order.php

class Order {
    private $id;
    private $items;
    public function __construct($id) {
        $this->id = $id;
    }
    public function addItem(Item $item) {
        $id = $item->getId();
        if(!array_key_exists($id, $this->items)) {
            $this->items[$id]['object'] = $item;
            $this->items[$id]['amount'] = $item;
        }
        $this->items[$id]['amount']++;
        return $this;
    }
}

■クライアントコード

define('IS_DEVELOP', true);
if(IS_DEVELOP) {
    $factory = new MockFactory();
}
else {
    $factory = new DbFactory();
}
$itemDao   = $factory->createItemDao();
$orederDao = $factory->createOrderDao();

// 処理
$itemDao->findById(23);
$orderDao->findById(29);

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

No comments yet.

RSS feed for comments on this post.TrackBack URL

Leave a comment