@blog.justoneplanet.info

日々勉強

Bridge Pattern

■コード

DataSourceInterface.php

interface DataSourceInterface {
    public function open();
    public function read();
    public function close();
}

FileDataSource.php

class FileDataSource implements {
    private $sourceName;
    private $handler;
    public function __construct($sourceName) {
        $this->sourceName = $sourceName;
    }
    public function open() {
        if(is_readable($this->sourceName) && $this->handler = fopen($this->sourceName)) {
            throw new Exception();
        }
    }
    public function read() {
        $buffer = array();
        while(!feof($this->handler)) {
            $buffer[] = fgets($this->handler);
        }
        return implode($buffer);
    }
}

Listing.php

class Listing {
    private $dataSource;
    public function __construct($dataSource) {
        $this->dataSource = $dataSource;
    }
    public function open() {
        $this->dataSource->open();
    }
    public function read() {
        return $this->dataSource->read();
    }
    public function close() {
        $this->dataSource->close();
    }
}

ExtendedListing.php

class ExtendedListing extends Listing {
    public function __construct($dataSource) {
        parent::__construct($dataSource);
    }
    public function readWithEncode($charset) {
        return htmlspecialchars($this->read, ENT_QUOTE, $charset);
    }
}

■クライアントコード

$list1 = new Listing(new FileDataSource('/home/hoge/fuga.txt'));
$list2 = new ExtendedListing(new FileDataSource('/home/hoge/piyo.txt'));
try {
    $list1->open();
    $list2->open();
    echo $list1->read();
    echo $list2->read();
    $list1->close();
    $list2->close();
}
catch (Exception $e) {

}

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

No comments yet.

RSS feed for comments on this post.TrackBack URL

Leave a comment