zoukankan      html  css  js  c++  java
  • 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 .= "
    ";
    
            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();
  • 相关阅读:
    网络协议栈(6)RFC793TCP连接时部分异常流程及实现
    网络协议栈(5)sendto/send返回成功意味着什么
    LeetCode——Detect Capital
    LeetCode——Find All Numbers Disappeared in an Array
    LeetCode——Single Number
    LeetCode——Max Consecutive Ones
    LeetCode——Nim Game
    LeetCode——Reverse String
    LeetCode——Next Greater Element I
    LeetCode——Fizz Buzz
  • 原文地址:https://www.cnblogs.com/happig/p/5365657.html
Copyright © 2011-2022 走看看