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 the class adapter pattern, the participant must include a PHP interface below as an example of a currency Exchange demo: Suppose there is a corporate website that sells software services and software products at the same time, all transactions are currently in the United States, so all calculations can be done in dollars. Now developers want to have a converter that can Deal with the exchange of dollars and euros without altering the original class of dollar turnover. By adding an adapter, the program can now be calculated in dollars or in euros. dollarcalc.php
<?phpclass dollarcalc{    private $dollar;    Private $product;    Private $service;    public $rate = 1;    Public Function Requestcalc ($productNow, $serviceNow)    {        $this->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
<?phpclass eurocalc{    private $euro;    Private $product;    Private $service;    public $rate = 1;    Public Function Requestcalc ($productNow, $serviceNow)    {        $this->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
<?phpinterface itarget{public    function requester ();}
Now developers can implement the requester () method, requesting the euro instead of the dollar. In the adapter design mode using inheritance, the adapter (Adapter) participates in both implementing ITarget interfaces and implementing 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
<?phpinclude_once (' eurocalc.php '); include_once (' itarget.php '); class Euroadapter extends Eurocalc implements itarget{Public    function __construct ()    {        $this->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. Since 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
<?phpinclude_once (' euroadapter.php '); include_once (' dollarcalc.php '); class client{public    function __ Construct ()    {        $euro = ' € ';        echo "District meta: $euro". $this->makeapapterrequest (New Euroadapter ()). ' <br/> ';        echo "USD: $:". $this->makedollarrequest (New Dollarcalc ()). ' <br/> ';    }    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 for building the class adapter. using the combined adapter modeThe 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 the class adapter mode, the adapter (Adapter) is an adaptor (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 may 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 the desktop-side class, which will require an adapter. This class uses a simple but very loose interface: iformat.php
<?phpinterface iformat{public    function Formatcss ();    Public function Formatgraphics ();    Public function Horizontallayout ();}
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
<?phpinclude_once (' iformat.php '); class Desktop implements iformat{public    function formatcss ()    {        echo "quote desktop.css<br/>";    }    Public Function Formatgraphics ()    {        echo "references desktop.png picture <br/>";    }    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 to adjust it to a mobile design. The following is a mobile-class mobile terminal with a mobile interface Imobileformat
<?phpinterface imobileformat{public    function Formatcss ();    Public function Formatgraphics ();    Public function Verticallayout ();}
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 the vertical layout, and the adapter is to solve the problem below gives a implementation of the Imoibleformat interface of the mobile class mobile.php
<?phpinclude_once (' imobileformat.php '); class Mobile implements imobileformat{public    function Formatcss ()    {        echo "references mobile.css<br/>";    }    Public Function Formatgraphics ()    {        echo "references mobile.png picture <br/>";    }    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
<?phpinclude_once (' iformat.php '); include_once (' mobile.php '); class Mobileadapter implements iformat{    Private $mobile;    Public function __construct (Imobileformat $mobileNow)    {        $this->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
<?phpinclude_once (' mobile.php '); include_once (' mobileadapter.php '); class client{    private $mobile;    Private $mobileAdapter;    Public function __construct ()    {        $this->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 ChangesPHP 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 did not change anything, only the adapter. If you need to use two incompatible interfaces in this case, the adapter mode works best. Adapters can be used to complete the "marriage" of the interface. You can think of the adapter as a marital counselor; Create a common interface to overcome differences between the two. Use This design pattern can lead to cooperation between the two, and avoids completely rewriting a part.

Design mode: Adapter mode

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.