Adapter mode: The interface of one class is converted into another interface that the customer wants, so that those classes that cannot work together because of incompatible interfaces can work together.
such as (borrow picture):
Set up the interface of the book
// Book Interface Interface bookinterface{ // page Flipping method public function turnpage () ; // Open Book Method Public function open ();}
// Paper Book Realization class class Implements bookinterface{ publicfunction turnpage () { echo " Paper book page. " "<br>"; } Public function Open () { echo "paper book Open". "<br>"; }}
Client testing:
// Client Testing $book New Book (); $book, open (); $book->turnpage ();
Output Result:
Paper books turn on the pages of paper books
At this point, you want to create a reusable class that can work with other unrelated classes or classes that are not predictable (that is, those that might not necessarily be compatible with the interface).
As follows:
// To be adapted to a target class kindle{ publicfunction turnpage () { echo "ebook Flip". "<br>"; } Public function Open () { echo "ebook Open". "<br>"; }}
Adapter
classKindleadapterImplementsbookinterface{protected $_kindle; Public function__construct ($obj) { $this->_kindle =$obj; } Public functionTurnpage () {$this->_kindle->Turnpage (); } Public functionOpen () {$this->_kindle->open (); }}
Client Testing
$kindle New Kindleadapter (new Kindle ()); $kindle, open (); $kindle->turnpage ();
Output results
ebook Open ebook Flip
Postscript:
This article is only for individual study notes collation, if there are flaws, please correct me!
PHP design mode (vii) adapter mode (Adapter for PHP)