PHP Mode Design Adapter mode

Source: Internet
Author: User
Most of the months have not written essays, mainly seniors to a lot of messy things, looking for work. Mainly blame their own strength, but also the main lack of light-eyed combat experience, it is difficult to arouse the interest of HR. So here or to do a small ads, I hope that there is a job, internship also does not matter, the most incompetent internships do not pay (I have been hit by the total No line). Location, but at the moment I can only read the rest of the year in Chengdu, anyway, write code anywhere is OK.

Ashamed to say, I always feel that I "know a lot of principles, that is not good this life." These blog share also no matter whether or not people look, always want to write their existing cognition, more hope to get the guidance of senior.

Return to the theme, before sharing the basic three design patterns , today to share another one we feel is not commonly used to, but this to the need for the big call convenient mode-adapter mode.

In this age when there is no object to shout " object -oriented", mastering Object -oriented will bring us unexpected convenience. Learn to program the small partner from the beginning can write a few lines of code to implement simple functions to later understand the combination of some repetitive operations to form a "function", and then the "function" and the combination of attributes to form a "class." Step by step, we are considering the improvement of the efficiency of the machine running code while also considering reducing the workload of the programmer. So what is the adapter model we're talking about today more focused on? Is the programmer's workload.

When will the adapter mode be used?

In fact, the simplest example is when we refer to a third-party class library. This class library, as the version changes, the API it provides may also change. If, unfortunately, one of the APIs referenced in your app has changed, you'll have to bite the bullet to change a lot of code, in addition to silently cursing "Wocao" in your heart.

Does it really have to be that way? As a routine, I will answer "no". We have adapter mode AH ~ ~

The adapter mode comes in handy when the interface changes.

Give me a chestnut.

If you can understand it through the simple description above, then you can only admire your ability to comprehend. The average person must still be unintelligible. To make it easy to understand, I cite an example of a Bo friend. The original address.

A beginning of harmony

Prune Toy Company specializes in the production of toys, production of toys are not limited to dogs, cats, lions, fish and other animals. Each toy can be "open mouth" and "Shut up" operation, respectively called the Openmouth and Closemouth method.

At this time, it is easy to think of the first definition of an abstract class toy, or even interface toy, these problems are not big, other classes to inherit the parent class, implement the parent class method. A harmony, confidence to glory.

Balance of destruction

In order to expand the business, now Prune toy company and Red JuJube remote control company, Red JuJube remote control company can use remote control equipment for the mouth of animals. But Red JuJube remote control company's remote control equipment is called the animal's Domouthopen and Domouthclose method. What the programmers of Prune toy company must do now is to upgrade the Toy series classes so that toy can invoke Domouthopen and Domouthclose methods.

Consider the implementation of the method, we very directly think, you need to I again in my parent class subclass to add such two methods to you. When you repeatedly add these two methods again and again in the subclass of the parent class, will you always think of such repetitive work that cannot be solved? When there are hundreds of of subclasses, the programmer will go crazy. Programmers tend to be more "lazy" than those who do not affect efficiency. In doing so the programmer will feel silly. (In fact, I used to be such a fool)

Abstractclasstoy{ PublicAbstractfunctionOpenmouth ();  PublicAbstractfunctionClosemouth (); //adding Domouthopen method to control interface of Red JuJube Telecontrol company PublicAbstractfunctionDomouthopen (); //adding Domouthclose method to control interface of Red JuJube Telecontrol company PublicAbstractfunctiondomouthclose ();}classDogextendstoy{ PublicfunctionOpenmouth () {Echo"Dog Open mouth\n"; }     PublicfunctionClosemouth () {Echo"Dog Open mouth\n"; }    //Added Method PublicfunctionDomouthopen () {$this-Domouthopen (); }    //Added Method PublicfunctionDomouthclose () {$this-Closemouth (); }}classCatextendstoy{ PublicfunctionOpenmouth () {Echo"Cat Open mouth\n"; }     PublicfunctionClosemouth () {Echo"Cat Open mouth\n"; }    //Added Method PublicfunctionDomouthopen () {$this-Domouthopen (); }    //Added Method PublicfunctionDomouthclose () {$this-Closemouth (); }}

More irritable

The programmer just finished code, drank saliva, suddenly another message came.

Prune toy company also want to work with the Green JuJube remote control company, because the green JuJube remote control equipment cheaper and stable. However, the remote control device of the Green JuJube Remote control company is called Animal's Opermouth ($type) method to realize the mouth controls. If $type is 0 then "shut up" and turn mouth.

Well, the programmer has to upgrade toy and its subclasses so that toy can invoke the Opermouth () method. No one is calm.

AbstractclassToy { PublicAbstractfunctionOpenmouth ();  PublicAbstractfunctionClosemouth ();  PublicAbstractfunctionDomouthopen ();  PublicAbstractfunctionDomouthclose (); //Add Domouthclose method to the control interface of Green JuJube Telecontrol company PublicAbstractfunctionOperatemouth ($type= 0); }    classDogextendsToy { PublicfunctionOpenmouth () {Echo"Dog Open mouth\n"; }         PublicfunctionClosemouth () {Echo"Dog Open mouth\n"; }         PublicfunctionDomouthopen () {$this-Domouthopen (); }         PublicfunctionDomouthclose () {$this-Closemouth (); }         PublicfunctionOperatemouth ($type= 0)      {          if($type= = 0) {              $this-Closemouth (); } Else {              $this-Operatemouth (); }      }  }    classCatextendsToy { PublicfunctionOpenmouth () {Echo"Cat Open mouth\n"; }         PublicfunctionClosemouth () {Echo"Cat Open mouth\n"; }         PublicfunctionDomouthopen () {$this-Domouthopen (); }         PublicfunctionDomouthclose () {$this-Closemouth (); }         PublicfunctionOperatemouth ($type= 0)      {          if($type= = 0) {              $this-Closemouth (); } Else {              $this-Operatemouth (); }      }  }

At this time, the programmer must be a brain to find a way, even if they are diligent, in case of purple jujube jujube Yellow jujube Mountain JuJube These remote control company all come, ignore their constantly increased workload do not say, this toy class but more and more big, one day programmers do not crash, the system will crash.

Where is the problem?

Write code like the above, code implementation violates the "open-closed" principle, a software entity should be open to the extension, the modification is closed. That is, when designing a module, it should be allowed to be extended without modification. Which means that every corpse is a small kingdom, you let me participate in your affairs this can, but you cannot modify my internal, unless my internal code can really be optimized.

Under this idea, we learned how to use inheritance, how to use polymorphism, and even how to achieve "high cohesion, low coupling."

Back to this question, we now face such a problem, the new interface method I want to implement, the old interface (toy abstract class) also cannot move, then must have a solution. That is to introduce a new class--the main character of our article--adapter. The adapter to complete the function is very clear, referencing the method of the existing interface to implement the new interface method. More like its name describes, your interface does not change, I will use the existing interface and you docking it.

Here, the solution is ready to go, put the code below.

  

 PhpAbstractclassToy { PublicAbstractfunctionOpenmouth ();  PublicAbstractfunctionClosemouth (); }    classDogextendsToy { PublicfunctionOpenmouth () {Echo"Dog Open mouth\n"; }         PublicfunctionClosemouth () {Echo"Dog Close mouth\n"; }  }    classCatextendsToy { PublicfunctionOpenmouth () {Echo"Cat Open mouth\n"; }         PublicfunctionClosemouth () {Echo"Cat Close mouth\n"; }  }//target role: Red JuJube remote Control companyInterfaceRedtarget { PublicfunctionDomouthopen ();  PublicfunctionDomouthclose (); }    //target role: Green JuJube remote control company andInterfaceGreentarget { PublicfunctionOperatemouth ($type= 0); }//class Adapter role: Red JuJube remote Control companyclassRedadapterImplementsRedtarget {Private$adaptee; function__construct (Toy$adaptee)      {          $this->adaptee =$adaptee; }        //SampleMethod1 method for delegating calls to Adaptee PublicfunctionDomouthopen () {$this->adaptee->Openmouth (); }         PublicfunctionDomouthclose () {$this->adaptee->Closemouth (); }  }    //class Adapter role: Green JuJube remote Control companyclassGreenadapterImplementsGreentarget {Private$adaptee; function__construct (Toy$adaptee)      {          $this->adaptee =$adaptee; }        //Operatemouth method for delegating calls to Adaptee:greentarget PublicfunctionOperatemouth ($type= 0)      {          if($type) {              $this->adaptee->Openmouth (); } Else {              $this->adaptee->Closemouth (); }      }  }classTestdriver { Publicfunctionrun () {//instantiation of a dog toy$adaptee _dog=NewDog (); Echo"Give the dog a red date adapter \ n"; $adapter _red=NewRedadapter ($adaptee _dog); //Mouth$adapter _red-Domouthopen (); //Shut Up$adapter _red-Domouthclose (); Echo"Put the dog on the green date adapter \ n"; $adapter _green=NewGreenadapter ($adaptee _dog); //Mouth$adapter _green->operatemouth (1); //Shut Up$adapter _green->operatemouth (0); }  }    $test=NewTestdriver (); $test->run ();

The final result is that the toy class and its subclasses implement different interfaces through the adapter without changing themselves.

Final summary

The interface of one class is converted into another interface that the customer wants, and those classes that are inherently incompatible and cannot work together can work together.

Adapter Mode Core idea: the operation of certain similar classes into a unified "interface" (here is the analogy of speaking)-adapter, or analogy to an "interface", unify or block the details of those classes. The adapter pattern also constructs a "mechanism" so that the "fit" class can be easily added and subtracted without modifying the code that interacts with the adapter, in line with the design principle of "reduce inter-code coupling".

Above

Series Articles:

PHP Pattern Design Single example mode

The Factory mode of PHP mode design

The registered tree mode of PHP mode design

PHP Mode Design Adapter mode

The above describes the PHP mode design adapter mode, including the aspects of the content, I hope the PHP tutorial interested in a friend helpful.

  • 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.