码迷,mamicode.com
首页 > 其他好文 > 详细

适配器模式

时间:2016-04-07 22:13:07      阅读:328      评论:0      收藏:0      [点我收藏+]

标签:

适配器模式

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

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

<?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();

 

适配器模式

标签:

原文地址:http://www.cnblogs.com/happig/p/5365657.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!