适配器模式
将某个类的接口转换成与另一个接口兼容。适配器通过将原始接口进行转换,给用户提供一个兼容接口,使得原来因为接口不同而无法一起使用的类可以得到兼容。
适配器的存在,就是为了将已存在的东西(接口)转换成适合我们需要、能被我们所利用的东西。
在现实生活中,适配器更多的是作为一个中间层来实现这种转换作用。比如电源适配器,它是用于电流变换(整流)的设备。
1 <?php 2 /** 3 * 本实例用于 将电子书 转换为 纸质书使用 4 */ 5 6 interface PaperBookInterface 7 { 8 public function open(); 9 public function turnPage(); 10 public function getPage(); 11 } 12 13 interface EBookInterface 14 { 15 public function unlock(); 16 public function pressNext(); 17 18 /** 19 * returns current page and total number of pages, like [10, 100] is page 10 of 100 20 * @return int[] 21 */ 22 public function getPage(); 23 } 24 25 26 /** 27 * This is the adapter here. Notice it implements BookInterface, 28 * therefore you don't have to change the code of the client which is using a PaperBook 29 */ 30 class EBookToPaperBookAdapter implements PaperBookInterface 31 { 32 private $_eBook; 33 34 public function __construct(\EBookInterface $eBook) 35 { 36 $this->_eBook = $eBook; 37 } 38 39 /** 40 * This class makes the proper translation from one interface to another. 41 */ 42 public function open() 43 { 44 $this->_eBook->unlock(); 45 } 46 47 public function turnPage() 48 { 49 $this->_eBook->pressNext(); 50 } 51 52 /** 53 * notice the adapted behavior here: EBookInterface::getPage() will return two integers, but BookInterface 54 * supports only a current page getter, so we adapt the behavior here 55 * 56 * @return int 57 */ 58 public function getPage() 59 { 60 return $this->_eBook->getPage()[0]; 61 } 62 } 63 64 65 66 67 68 69 class Book implements PaperBookInterface 70 { 71 /** 72 * @var int 73 */ 74 private $page; 75 76 public function open() 77 { 78 $this->page = 1; 79 } 80 81 public function turnPage() 82 { 83 $this->page++; 84 } 85 86 public function getPage(): int 87 { 88 return $this->page; 89 } 90 } 91 92 93 class Kindle implements EBookInterface 94 { 95 /** 96 * @var int 97 */ 98 private $page = 1; 99 100 /** 101 * @var int 102 */ 103 private $totalPages = 100; 104 105 public function pressNext() 106 { 107 $this->page++; 108 } 109 110 public function unlock() 111 { 112 } 113 114 /** 115 * returns current page and total number of pages, like [10, 100] is page 10 of 100 116 * 117 * @return int[] 118 */ 119 public function getPage() 120 { 121 return [$this->page, $this->totalPages]; 122 } 123 } 124 125 126 127 128 129 $kindle = new Kindle(); 130 $book = new EBookAdapter($kindle); 131 132 $book->open(); 133 $book->turnPage();