PHP design mode (vii) adapter mode (Adapter for PHP)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.