@blog.justoneplanet.info

日々勉強

PHPでStrategyパターン

アルゴリズムをクラスとして定義し、対象によって切り替える。

■実装

class ItemDataContext
{
    private $_strategy;

    public function __construct(ReadItemDataStrategy $strategy){
        $this->_strategy = $strategy;
    }

    public function getItemData(){
        return $this->strategy->getData();
    }
}
abstract class ReadItemDataStrategy
{
    private $_filename;
    public function __construct($filename)
    {
        $this->_filename = $filename;
    }

    public function getData()
    {
        if(!is_readable($filename = $this->getFilename())){
            throw new Exception('is not readable : ' . $filename);
        }
        return $this->readData($filename);
    }

    public function getFilename()
    {
        return $this->_filename;
    }

    protected abstract function readData($filename);
}

ReadFixedLengthDataStrategy.php

class ReadFixedLengthDataStrategy extends ReadItemDataStrategy
{
    protected function readData($filename){
        // implementation
    }
}

ReadTabSeparatedDataStrategy.php

class ReadTabSeparatedDataStrategy extends ReadItemDataStrategy
{
    protected function readData($filename){
        // implementation
    }
}

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

No comments yet.

RSS feed for comments on this post.TrackBack URL

Leave a comment