适配器模式
就是不修改原有类的基础上 加一个中间转换层,以使其符合新需求
说白了,就是对原有类的扩展,怎么扩展,继承呗
例如下:
1 <?php 2 3 //最原始的错误处理 4 class Error { 5 public $_error; 6 7 public function __construct($error) { 8 $this->_error = $error; 9 } 10 11 public function getError() { 12 return $this->_error; 13 } 14 } 15 16 class Log { 17 public $errObj; 18 19 public function __construct(Error $obj) { 20 $this->errObj = $obj; 21 } 22 23 public function writeLog() { 24 fwrite(STDERR, $this->errObj->getError()); 25 } 26 } 27 28 $err = new Error('1:wrong!'); 29 30 $log = new Log($err); 31 $log->writeLog(); 32 33 //需求变了,本着那啥和啥的原则,类是不能轻易改动的.... 34 class LogCsv{ 35 public $csvFile = 'log.txt'; 36 37 public $errObj; 38 39 public function __construct(Error $obj) 40 { 41 $this->errObj = $obj; 42 } 43 44 public function writeLog() 45 { 46 $line = ''; 47 $line .= $this->errObj->getNum(); 48 $line .=' '; 49 $line .= $this->errObj->getText(); 50 51 file_put_contents($this->csvFile, $line); 52 } 53 } 54 55 //错误处理适配器 56 class ErrorAdapter extends Error{ 57 public $num; 58 public $text; 59 60 public function __construct($error) 61 { 62 $arr = explode(':', $error); 63 $this->num = $arr[0]; 64 $this->text = $arr[1]; 65 } 66 67 public function getNum() 68 { 69 return $this->num; 70 } 71 public function getText() 72 { 73 return $this->text; 74 } 75 } 76 $err = new ErrorAdapter('1:wrong!'); 77 78 $log = new LogCsv($err); 79 $log->writeLog();