工大学子

php设计模式之适配器模式

适配器模式

适配器设计模式的目标是有助于面向对象的代码,该模式下可以为独享接口创建对话,

虽然可以修改现有代码从而采用新功能所期望的方式运行,但我们最好还是创建一个适配器对象。

<?php
/**
 * Adapter.php
 * 适配器模式
 */

/**
 * 旧接口
 */
class errorObject
{
    private $_error;
    public function __construct($error){
        $this->_error = $error;    
    }

    public function getError(){
        return $this->_error;
    }
}
/**
 * 旧方法
 */
class logToConsole
{
    private $_errorObject;

    public function __construct($errorObject){
        $this->_errorObject = $errorObject;
    }

    public function write(){
        fwrite(STDERR,$this->_errorObject->getError());
    }
}

/** create the new 404 error object */
$error = new errorObject("404:Not Found");
$log = new logToConsole($error);
$log->write();


/**
 * 新方法
 */
class logToCSV
{
    const CSV_LOCSTION = 'log.csv';
    private $_errorObject;

    public function __construct($errorObject){
        $this->_errorObject = $errorObject;
    }

    public function write(){
        $line = $this->_errorObject->getErrorNunber();
        $line .= ',';
        $line .= $this->_errorObject->getErrorText();
        $line .= "\n";

        file_put_contents(self::CSV_LOCSTION,  $line, FILE_APPEND);
    }
}
/**
 * 制作适配器,重新组装数据,使之能应用于新方法
 */
class logToCSVAdapter extends errorObject
{
    private $_errorNunber, $_errorText;

    public function __construct($error){
        parent::__construct($error);
        $parts = explode(':', $this->getError());
        $this->_errorNunber = $parts[0];
        $this->_errorText = $parts[1];
    }

    public function getErrorNunber(){
        return $this->_errorNunber;
    }

    public function getErrorText(){
        return $this->_errorText;
    }
}

/**create the new 404 error object adapted for csv  */
$error = new logToCSVAdapter("404:Not Found");
$log = new logToCSV($error);
$log->writer();

 

posted @ 2016-04-07 21:53  飞天小莫  阅读(146)  评论(0编辑  收藏  举报
飞天小莫