Design Mode (10) Adapter Mode

Source: Internet
Author: User

Design Mode (10) Adapter Mode

I. Problem Introduction

Speaking of adapter, it is very common in our life. For example, if you are on a business trip to Japan, you will find that the pressure of the outlets in Japan is v, our cell phone charger and laptop charger are both 220 V, so you won't be able to charge when you arrive in Japan. What should we do at this time, of course, a boost transformer is used to increase the voltage to 220 V, so that our mobile phone can use an unusable socket through a transformer (adapter.

For example, in some countries, the sockets are all three holes, and most of our mobile phones are two holes. You cannot directly plug the charger into the socket. In this case, we can use an adapter, the adapter itself is a three-hole plug, which can be directly inserted into the three-hole plug, the adapter itself can provide a two-hole socket, and then our mobile phone charger can be inserted into the adapter, in this way, we can only insert the plug into two holes to use the three-hole socket.

This problem also exists in our object-oriented architecture. Assume that a software system can be used together with a new vendor class library, but the interfaces designed by the new vendor, different from the interfaces of the old manufacturer, it is like this:

You don't want to change the existing code to solve this problem (and you cannot change the vendor's Code ). So what should we do? You can write a class to convert the interfaces of new vendors into the interfaces you want. <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4NCjxwPjxpbWcgYWx0PQ = "here write picture description" src = "http://www.bkjia.com/uploads/allimg/151205/042H639B-1.png" title = "\"/>

This adapter works like a man-in-the-middle, which converts a customer's request into a vendor-class understandable request.

In this way, you can use the originally mismatched class library without changing the existing code.

2. concepts related to the adapter Mode

After the three examples above, we can summarize the usage process of the adapter mode:
1. The customer sends a request to the adapter by calling the method of the adapter through the target interface.
2. the adapter uses the adapter interface to convert the request to one or more called interfaces of the adapter.
3. The customer receives the call results, but does not notice that all of these are suitable for conversion.

Therefore, the formal definition of the adapter mode is:

The adapter mode converts an interface of a class into another interface that the customer expects. The adapter allows classes that are not compatible with the original interface to work together.

Iii. Object Adapter

There are two types of adapters: Object Adapter and class Adapter. The two types work in different ways. The Object Adapter uses a combination method. In the Adapter, a reference of the original object (Adaptee) is retained. The implementation of the Adapter is to delegate the method in the Target to the Adaptee object, use the method in Adaptee to implement the method in Target.

The advantage of this type is that Adpater only needs to implement the method in Target.

Now let's look at how to use the adapter mode by taking the Turkey as a duck.

Package com. designpattern. adapter. object; public abstract class Duck {/*** */public abstract void quack (); public abstract void fly ();}
Package com. designpattern. adapter. object; public abstract class Turkey {/*** Turkey name */public abstract void gobble (); public abstract void fly ();}
package com.designpattern.adapter.object;public class WildTurkey extends Turkey {    public void gobble() {        System.out.println(Gobble gobble);    }    public void fly() {        System.out.println(I'm flying a short distance);    }}
Package com. designpattern. adapter. object;/*** impersonate a Duck with a Turkey * @ author 98583 **/public class TurkeyAdapter extends Duck {/*** reserve the reference of the turkey */Turkey turkey; public TurkeyAdapter (Turkey turkey) {this. turkey = turkey;}/*** use the call of a turkey to call a duck */public void quack () {turkey. gobble ();}/*** how to fly a duck using the method of flying a Turkey */public void fly () {for (int I = 0; I <5; I ++) {turkey. fly ();}}}
Package com. designpattern. adapter. object;/*** impersonate a duck with a turkey * @ author 98583 **/public class Client {public static void main (String [] args) {WildTurkey turkey = new WildTurkey (); duck turkeyAdapter = new TurkeyAdapter (turkey); System. out. println (The Turkey says ...); turkey. gobble (); turkey. fly (); System. out. println (The TurkeyAdapter says ...); testDuck (turkeyAdapter);} static void testDuck (Duck duck) {duck. quack (); duck. fly ();}}

Duck and Turkey have similarities. They both fly. Although they are not far from flying, their sounds are not the same. Now we have a turkey class, abstract classes with ducks are called interfaces. Our adapter inherits from the duck class and retains the reference of the Turkey. It overrides the flying and calling methods of the duck, but is implemented by entrusting the turkey method. On the client side, we can pass a turkey object to the adapter and use it as a duck.

Iv. Class adapters

Unlike object adapters, class adapters are implemented through class inheritance. Adpater inherits all the methods in Target and Adaptee and rewrite them to implement the methods in Target.

The disadvantage of this method is that the methods in Target and Adaptee must be implemented. Because Java does not support multi-inheritance, the Target is usually designed as an interface, and the Adapter inherits from Adaptee and then implements the Target interface.

We use the class adapter to simulate a duck with a turkey.

Package com. designpattern. adapter. classmethod;/*** Because Java does not support multi-inheritance, therefore, the Target is usually declared as an interface * @ author 98583 **/public interface Duck {/***, which is called */public void quack (); public void duckFly ();}
Package com. designpattern. adapter. classmethod;/*** the current abstract class of the Turkey class * @ author 98583 **/public abstract class Turkey {/*** the Turkey name */public abstract void gobble (); public abstract void turkeyFly ();}
Package com. designpattern. adapter. classmethod;/*** impersonate a duck with a turkey instead of retaining reference to the turkey class, method to implement the Duck and Turkey Classes * @ author 98583 **/public class TurkeyAdapter extends Turkey implements Duck {/*** use the call of Turkey to implement the call of ducks */public void quack () {gobble ();}/*** the method of flying a duck using the turkey method */public void turkeyFly () {for (int I = 0; I <5; I ++) {System. out. println (I'm flying a short distance) ;}/ *** use the turkey method to implement the duck Method */public void duckFly () {turkeyFly ();}/*** Turkey call */public void gobble () {System. out. println (Gobble gobble );}}
Package com. designpattern. adapter. classmethod;/*** impersonate a Duck with a Turkey * @ author 98583 **/public class Client {public static void main (String [] args) {Duck turkeyAdapter = new TurkeyAdapter (); system. out. println (The TurkeyAdapter says ...); testDuck (turkeyAdapter);} static void testDuck (Duck duck) {duck. quack (); duck. duckFly ();}}

In fact, the effects of the two methods are the same, but they are different. Java does not support multi-inheritance. Therefore, the Duck is declared as an interface. The Adapter inherits from the turkey class and implements the Duck method. However, the method to implement Duck is no longer an object to be delegated to the turkey class, instead, you can directly call the turkey method. Because the turkey method is implemented in the Adapter, you can call it directly.

5. Default Adapter

The story of Ruda shaving demonstrates the role of the default adapter. Generally, monks eat fast, read Classics, meditate, hit clocks, and XI Wu, but Ruda only drinks and drinks Xi Wu, so 'ruda cannot shave (it cannot be used as a monk ), if Ruda can be used as a monk, it is necessary for him to implement all the methods of the monk, but when doing so, Ruda is not Ruda. We can find someone in the middle. For example, Ruda is one of the stars. We can let the stars implement all the methods of monk and let Ruda inherit from the stars. The Code is as follows:

This is the defined monk interface, and should both do the following.

package com.designpattern.adapter.defaultmethod;public interface Monk {    public void chizha();    public void nianjing();    public void dazuo();    public void zhuangzhong();    public void xiwu();}

This is a star class that provides an empty implementation for each method. Other child classes inherited from this class can override the parent class method.

package com.designpattern.adapter.defaultmethod;public abstract class Star implements Monk{    public void chizha(){}    public void nianjing(){}    public void dazuo(){}    public void zhuangzhong(){}    public void xiwu(){}}

Ruda inherits from tianxing and adds the drinking method.

Package com. designpattern. adapter. defaultmethod; public class Luda extends Star {public void xiwu () {System. out. println (Ruda xiwu);} public void hejiu () {System. out. println (Ruda drinking );}}

We can see that through the tianxing class (default adapter), Ruda does not need to implement the methods that it does not need.

Vi. Advantages and Disadvantages

Advantages:

Decouple the target class and adaptation class, and introduce an adapter class to reuse the existing adapter class without modifying the original code. The class transparency and reusability are added. The specific implementation is encapsulated in the adapter class, which is transparent to the client class and improves the reusability of the adapter. The flexibility and scalability are very good. By using the configuration file, you can easily replace the adapter, or you can add a new adapter class without modifying the original code, it fully complies with the "open and closed principles ".

The class adapter mode also has the following advantages:
Because the adapter class is a subclass of the adapter class, you can replace some adaptive methods in the adapter class to make the adapter more flexible.

The Object Adapter mode also has the following advantages:
An Object Adapter can adapt multiple different adaptors to the same target, that is, the same adapter can adapt both the adapter class and its subclass to the target interface.

Disadvantages:
The disadvantages of the class adapter mode are as follows:
For languages such as Java and C # that do not support multiple inheritance, a maximum of one adaptor class can be adapted at a time, and the target abstract class can only be an abstract class, not a specific class, its usage has certain limitations. It is not allowed to adapt both an adapter class and its subclass to the target interface.

The disadvantages of Object Adapter mode are as follows:
Compared with the class adapter mode, it is not easy to replace the method of the adapter class. If you must replace one or more methods of the adaptor class, you have to first create a subclass of the adaptor class and replace the methods of the adaptor class, then, the sub-classes of the adaptor class are used as the real adaptors to adapt. The implementation process is complicated.

VII. Applicable Environment

1. The system needs to use existing classes, and the interfaces of these classes do not meet the requirements of the system.
2. Create a reusable class for some classes that are not highly correlated with each other, including some classes that may be introduced in the future.

 

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.