概念
适配器设计模式只是将某个对象的接口适配为另一个对象所期望的接口。
UML图
###代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
| class errorObject { private $_error; public function __construct($error) { $this->_error = $error; }
public function getError() { return $this->_error; } }
class LogToCsvErrorObject extends errorObject{ private $error_num; private $error_msg;
public function __construct($error) { parent::__construct($error); $error = $this->getError(); $parts = explode(":",$error); $this->error_num = $parts[0]; $this->error_msg = $parts[1]; } public function getErrorNum() { return $this->error_num; }
public function getErrorMsg() { return $this->error_msg; } }
class LogToConsole { private $_errorObject;
public function __construct(errorObject $errorObject) { $this->_errorObject = $errorObject; }
public function write() { fwrite(STDERR,$this->_errorObject->getError()); } }
class LogToCSV { private $_errorObject;
public function __construct(LogToCsvErrorObject $errorObject) { $this->_errorObject = $errorObject; }
public function write() { $error_num = $this->_errorObject->getErrorNum(); $error_msg = $this->_errorObject->getErrorMsg();
fwrite(STDERR,$error_msg."错误码:".$error_num); } }
$error_obj = new LogToCsvErrorObject("404:NOT FOUND");
(new LogToCSV($error_obj))->write();
|