策略模式(strategy)

<?php
/**
 * Created by PhpStorm.
 * User: zhangheg
 * Date: 2018/5/6
 * Time: 10:05
 * 设计模式
 */
/**
 * 设计模式的根本意图是适应需求的变化
 * 增加功能不修改原来的代码
 *   基本原则
 * 单一职责:
 * 开放封闭
 * 策略模式(strategy)
 * thinkphp 多种数据库策略模式,记录日志缓存策咯模式 uml图()
 * http://design-patterns.readthedocs.io/zh_CN/latest/read_uml.html
 */


interface FileExporter
{
    /**
     * 写文件
     */
    public function writeFile($fileName,$data);

}


class XmlFile implements FileExporter
{

    public function writeFile($fileName,$data)
    {
        $xml=$this->arrayToXml($data);
        file_put_contents($fileName.'.xml', $xml);
    }

    private function arrayToXml($arr)
    {
        $xml = '<xml version="1.0" standalone="yes">';
        foreach ($arr as $item) {
            $xml .= "\n <item>";
            foreach($item as $key => $val){
                $xml .="\n    <$key>$val</$key>";
            }
            $xml .="\n </item>";
        }
        $xml .= "\n</xml>";
        return $xml;
    }
}

class CvsFile implements FileExporter
{
    public function writeFile($fileName,$data)
    {

        $fh=fopen($fileName.'.csv', 'w');
        foreach ($data as $key => $value) {
            fputcsv($fh, $value);
        }
        fclose($fh);
    }
}

class JsonFile implements FileExporter{
    public function writeFile($fileName, $data)
    {
        // TODO: Implement writeFile() method.
        if(is_array($data)){
            $data = json_encode($data);
        }else{
            file_put_contents('log.txt','数据格式只支持数组');
        }
        file_put_contents($fileName.".json",$data);
    }
}



class MyTool{

    private $fileName;
    private $exporter;

    public function __construct($fileName='default'){
        $this->fileName=$fileName;
    }

    public function setFileExporter(FileExporter $exporter){
        $this->exporter=$exporter;
    }

    public function export($data){
        $this->exporter->writeFile($this->fileName,$data);
        echo "done!";
    }


}


$data = [
    ['date'=>'2011-04-21','wu'=>'test'],
    ['date'=>'2014-04-21','wu'=>'good'],
    ['date'=>'2011-12-22','wu'=>'great'],
    ['date'=>'2012-05-21','wu'=>'hahah'],
    ['date'=>'2013-08-13','wu'=>'test'],
    ['date'=>'2011-04-25','wu'=>'yes'],
    ['date'=>'2014-04-14','wu'=>'no'],
];

$tool=new MyTool();
//$tool->setFileExporter( new XmlFile() );
//$tool->export($data);
//
//$tool->setFileExporter( new CvsFile() );
//$tool->export($data);
$tool->setFileExporter(new JsonFile());
$tool->export($data);

发表评论

电子邮件地址不会被公开。 必填项已用*标注