企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
### 概述 将一个类的接口转换成可应用的兼容接口。适配器使原本由于接口不兼容而不能一起工作的那些类可以一起工作。 ### 实例 ~~~ interface BookInterface{ public function open(); public function turnPage(); public function getPage(); } class Book implements BookInterface{ private $page; public function open() { $this->page = 1; } public function turnPage() { $this->page++; } public function getPage():int { return $this->page; } } interface EBookInterface { public function unlock(); public function pressNext(); public function getPage(); } class Kindle implements EBookInterface{ private $page = 1; private $totalPages = 100; public function unlock() { } public function pressNext() { $this->page++; } public function getPage():array { return [$this->page,$this->totalPages]; } } class EBookAdapter implements BookInterface{ private $eBook; public function __construct(EBookInterface $eBook) { $this->eBook = $eBook; } public function open() { $this->eBook->unlock(); } public function turnPage() { $this->eBook->pressNext(); } public function getPage():int { return $this->eBook->getPage()[0]; } } $book = new Book(); $book->open(); $book->turnPage(); var_dump($book->getPage()); $kindle = new Kindle(); $book = new EBookAdapter($kindle); $book->open(); $book->turnPage(); $book->turnPage(); $book->turnPage(); var_dump($book->getPage()); ~~~ 结果 ~~~ 2 4 ~~~