Design mode: Adapter mode

Source: Internet
Author: User
Tags mysql code
The adapter is easy to understand, most families have a mobile phone adapter that is used to charge the mobile phone, which is an adaptor. If you have only a USB connector, you cannot plug your mobile phone into a standard socket. In fact, an adapter must be used, one end connected to the USB plug, and the other end connected to the socket. Of course, you can take out the electrical tools, modify the USB connector, or reinstall the socket, but this will bring a lot of extra work and may break the connector or socket. Therefore, the most desirable method is to find an adapter. The same is true for software development.

class Adapter mode ( using inheritance)

The class adapter pattern is simple, but the class adapter pattern is less flexible than the object adapter pattern, because the class adapter is simple because the adapter (Adapter) inherits functionality from the adaptive (adaptee), so the code that needs to be written in the adaptation mode is relatively small.

Because the class adapter pattern contains double inheritance, PHP does not support double inheritance, but fortunately, PHP can use interfaces to simulate double inheritance, the following is a correct structure, not only inherits a class, but also inherits an interface

Class ChildClass extends ParentClass implements isomeadapter{    }

When implementing class Adapter mode, participants must include a PHP interface

The following example shows a currency exchange:

Suppose there is a corporate website that sells software services and software products at the same time, all transactions are currently conducted in the United States, so all calculations can be done in dollars. Now developers want to have a converter that can handle dollar and euro conversions without changing the original class of dollar transactions. By adding an adapter, The procedure can now be calculated in dollars or in euros.

dollarcalc.php

 
  Product = $productNow;        $this->service = $serviceNow;        $this->dollar = $this->product + $this->service;        return $this->requesttotal ();    }    Public Function Requesttotal ()    {        $this->dollar *= $this->rate;        return $this->dollar;    }}

Looking at this class, you can see that there is a property $rate,requesttotal () method that uses $rate to calculate the amount of a transaction. In this version, this value is set to 1, in fact the total amount does not need to be good to exchange rate, However, $rate variables are convenient if you want to offer discounts to customers or to add additional services or product surcharges. This class is not part of the Fit mode, but it is a starting point.

The demand has changed.

Now the customer's company wants to develop to Europe, so need to develop an application, can complete the same calculation in euro. You want this euro calculation to be like Dollarcalc, all you have to do is change the variable name.

eurocalc.php

 
  Product = $productNow;        $this->service = $serviceNow;        $this->euro = $this->product + $this->service;        return $this->requesttotal ();    }    Public Function Requesttotal ()    {        $this->euro *= $this->rate;        return $this->euro;    }}

Next, insert the rest of the app into the Eurocalc class. However, because all of the customer's data is in dollar terms. In other words, if you do not re-develop the entire program, you cannot "insert" the euro calculation in the system. But you don't want to do this. In order to join EUROCALC, you need an adapter: Just like looking for an adapter to fit a European socket, you can create an adapter that enables your system to use the euro. Fortunately, the class adapter is designed for this scenario. You first need to create an interface. In this class diagram, this interface is named ITarget. It has only one method requester (). Requester () is an abstract method that is implemented by the implementation of the interface.

itarget.php

 

Now developers can implement the requester () method, requesting euros instead of dollars.

In the use of inherited adapter design patterns, the adapter (Adapter) participates in both implementing the ITarget interface and implementing the specific class Eurocalc. Creating Euroadapter does not require much work, as most of the work is already done in the Eurocal class. Now all you have to do is implement the request () method so that it can convert the dollar value to the euro value.

euroadapter.php

 
   Requester ();    }    Public Function requester ()    {        $this->rate = 0.8111;        return $this->rate;    }}

In a class adaptation pattern, a specific class inherits another concrete class, and the design pattern of this structure is seldom seen, and most design patterns are almost inherited from an abstract class, and the class implements its abstract methods and properties as needed. In other words, when it comes to inheritance, it is the concrete class that inherits the abstract class.

Because both an interface and a class are implemented, the Euroadapter class has both the interface and the specific class interface. By using the requester () method, the Euroadapter class can set the rate value (the exchange ratio) so that it can use the function of the adapter and make any changes to the meta.

The following defines a client class that makes requests from the Euroadapter and Dollarcalc classes. As you can see, the original Dollarcalc still works well, but it has no itarget interface.

client.php

 
   Makeapapterrequest (New Euroadapter ()). '
'; echo "USD: $:". $this->makedollarrequest (New Dollarcalc ()). '
'; } Private Function Makeapapterrequest (ITarget $req) { return $req->requestcalc (40,50); } Private Function Makedollarrequest (Dollarcalc $req) { return $req->requestcalc (40,50);} } $woker = new Client ();

The results of the operation are as follows:

Euros:€72.999dollars: $: 90

As you can see, both the dollar and the euro can be handled, which is the convenience of the adapter mode.

This calculation is simple, and if it is for more complex computations, the inheritance is required to provide the necessary interface and implementation of the target interface to build the class adapter

Using the combined adapter mode

The object adapter pattern uses a combination rather than inheritance, but it also accomplishes the same goal. By comparing the two versions of the adapter pattern, you can see the pros and cons of each. In the case of class adapter mode, the adapter can inherit most of the functionality it needs, just slightly tuned through the interface. In object adapter mode, the adapter (Adapter) participates in the use of the ligand (adaptee) and implements the target interface. In class adapter mode, the adapter (Adapter) is an adaptive (adaptee) and implements the target interface.

Example: moving from a desktop environment to a mobile environment

PHP programmers often encounter the problem of adapting to a mobile environment. Not long ago, you might just want to consider providing a website to accommodate a variety of different desktop environments. Most desktops use one layout, and the designer makes it more beautiful. For mobile devices, designers and developers need to rethink not only the design elements of the page display in the desktop and mobile environments, but also how to switch from one environment to another.

First of all, look at desktop-class desktops (it will require an adapter). This class uses a simple but very loose interface:

iformat.php

  

It supports CSS and image selection, but one method indicates a horizontal layout, and we know that this layout does not apply to small mobile devices. The desktop class that implements this interface is given below

desktop.php

 
    ";    }    Public Function Formatgraphics ()    {        echo ' reference desktop.png picture
"; } Public Function Horizontallayout () { echo ' Desktop: horizontal layout '; }}

The problem is that the layout is too wide for a small mobile device. So our goal is to still use the same content, but adjust it to a mobile design.

Here's a look at mobile-class mobility

First the mobile end has a mobile port interface

Imobileformat

   

As you can see, the Imobileformat interface and the Iformat interface are not the same, that is, incompatible, one contains the method Horizontallayout (), the other contains the method Verticallaout (), the difference is very small, the main difference is: Desktop design can be horizontal multi-column layout, and mobile design to use vertical layout, and adapter is to solve this problem

The following shows a mobile class that implements the Imoibleformat interface

mobile.php

 
     ";    }    Public Function Formatgraphics ()    {        echo ' reference mobile.png picture
"; } Public Function Verticallayout () { echo ' Mobile: Vertical layout '; }}

The mobile class and the desktop class are very similar, but the pictures and CSS references are different

Next, we need an adapter that combines the desktop and the mobile class

mobileadapter.php

 
     Mobile = $mobileNow;    }    Public Function Formatcss ()    {        $this->mobile->formatcss ();    }    Public Function Formatgraphics ()    {        $this->mobile->formatgraphics ();    }    Public Function Horizontallayout ()    {        $this->mobile->verticallayout ();}    }

As you can see, an instance of the mobile object is provided when the Mobileadapter is instantiated. Also note that Imobileformat is used in the type hint to ensure that the parameter is a mobile object. Interestingly, Adapter participants include the Verticallayout () method by implementing the Horizontallayout () method. In fact, all mobileadapter methods are packaged with an mobile method. It happens that One of the methods in the adapter participant is not in the adapter interface (Verticallayout ()); they may be completely different, and the adapter simply wraps them in a method of the adapter interface (Iformat).

Client Invocation (client)

client.php

 
     Mobile = new mobile ();        $this->mobileadapter = new Mobileadapter ($this->mobile);        $this->mobileadapter->formatcss ();        $this->mobileadapter->formatgraphics ();        $this->mobileadapter->horizontallayout ();    }} $worker = new Client ();

The client class in adapter mode must wrap an instance of Adaptee (Mobile) in order to integrate into the adapter itself. When instantiating adapter, The client uses adatee as a parameter to complete the instantiation of the adapter. So the customer must first create a adapter object (new Mobile ()), and then create a adapter (new Mobileadapter ($this Mobile)).

Most requests from the client class are sent through Mobileadapter. But at the end of the code, he used an instance of the mobile class.

Adapters and changes

PHP programmers should be faced with changes. Different versions of PHP will change, may add new features, and may also remove some features. And with PHP's big and small changes, MySQL is also changing. For example, MySQL's expansion pack is upgraded to Mysqli, and PHP developers need to adjust accordingly. Instead, use the new API in Mysqli. Is this suitable for adapter mode? It may not be suitable. The adapter may be applicable and may not be applicable, depending on how your program is configured. Of course you can rewrite all the connection and interaction code, but this is not the intention of the adapter mode, which is like reinstalling the USB connector Want to plug it into a standard wall outlet. However, if all the original MySQL code is in the module, you can modify the module (class) and switch to a new module with the same interface. Just use mysqli instead of MySQL. I don't think the swap is equivalent to the adapter, but the truth is the same, in adapter mode, The original code has nothing to change, only the adapter is changed.

If you need to use a combination of two incompatible interfaces, in this case, the adapter mode works best. Adapters can be used to complete the "marriage" of the interface. The adapter can be thought of as a marital consultant; by creating a public interface to overcome the differences between the two. This design pattern can be used to promote cooperation And avoid completely rewriting a part.

The above describes the design pattern: Adapter mode, including the aspects of the content, I hope to be interested in PHP tutorial friends 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.