Java design mode--Adapter (Adapter)

Source: Internet
Author: User

# Tags: Read blog


Adapter Pattern/wrapper Pattern

When do I need a package? Must be you give me, the existing service provides bad use, I need to give you to carry on the packaging and then use, or suitable for use after.

In Android, can the list of data be placed directly above the view? No, that's why I got a adapter. This is a package class that can be put on a view, or a data source for view.

Your laptop needs 12V of DC power, but your home only 220V AC or 110V AC power, provided, not required, not directly used, is not to fit, packaging I can use AH.

This thinking put on the code is that you provide a interface (class) at all, no way I have to engage in a Aadapter class or Awrapper class or ainterface to you to wrap a layer, or the appropriate match, let's call B, then I want to use a, directly with a of the adaptation B is good.


Well, you can go and see the author's original. (I will tell you that the author really did not give such a good example, of course, I said, my level is not above the author, this is only a question after the study of the multi-party)


original reproduced from:http://blog.csdn.net/guolin_blog/article/details/9400141

Early this morning, your leader rushed to find you: "Quick, quick, urgent task!" Recently ChinaJoy is about to start, and the boss asked for an intuitive way to see the number of people in each of our new online games. ”

You looked at the date, didn't you! This is where it's going to start, and it's already started! How could it be too late?

"It's okay. "Your leader Comfort you:" The function is actually very simple, the interface has been provided, you just need to call on the line. ”

Well, you reluctantly accepted, for this sudden new demand, you are already accustomed to.

Your leader to you a specific description of the demand, your game currently has three clothing, a service has been open for some time, the second and three are new clothes. Design of the interface is very light, you only need to call Utility.getonlineplayercount (int), the number of incoming per service can be obtained to the corresponding amount of online players, such as the incoming 1, the second pass 2, the three services are passed in 3. If you pass in a non-existent service, it will return-1. Then you just have to assemble the resulting data into XML, and the specific display function is done by your leader.

Well, it sounds like it's not very complicated, and if it's time to start the work now, you're going to have to hit the code right away.

First define an interface Playercount for counting the number of people online, with the following code:

Public interface Playercount {String getservername ();    int Getplayercount (); }

The three statistical classes are then defined to implement the Playercount interface, which corresponds to three different services, as shown below:

public class serverone implements  PlayerCount {         @Override        public string getservername ()  {           return  "one service";      }          @Override       public int getplayercount ()  {           return utility.getonlineplayercount (1);       }    } 
public class servertwo implements  PlayerCount {         @Override        public string getservername ()  {           return  "Second Service";      }          @Override       public int getplayercount ()  {           return utility.getonlineplayercount (2);       }    } 
public class Serverthree implements Playercount {@Override public String getServerName () {return "three      Service ";      } @Override public int getplayercount () {return utility.getonlineplayercount (3); }    }

Then define a Xmlbuilder class that encapsulates the data for each service in XML format, with the following code:

public class xmlbuilder {         public static string buildxml (PlayerCount player)  {          stringbuilder builder = new  stringbuilder ();           builder.append ("<root> ");           builder.append (" <server> "). Append ( Player.getservername ()). Append ("</server>");           Builder.append ("<player_count"). Append (Player.getplayercount ()). Append ("</player_count>");           builder.append ("</root>");           return builder.tostring ();      }     } 

In that case, all the code is done, and if you want to see the number of players online, just call:

Xmlbuilder.buildxml (New ServerOne ());

View two online players only need to call:

Xmlbuilder.buildxml (New Servertwo ());

To see the number of players in the three-line game only call:

Xmlbuilder.buildxml (New Serverthree ());

Hey? You find that when you look at the number of players online, the return value is always-1, and it's normal to look at the second and the third suits.

You have to call up your leader: "I feel I write the code is not a problem, but query one serving the number of players online always return-1, why this?" ”

Oh "Your leader suddenly reminds me," This is my problem, before you explain clearly. Since one of our services has been open for some time, the ability to query the number of online players has long been available, using the Serverfirst class. At that time wrote Utility.getonlineplayercount () This method is mainly aimed at the new two and three services, did not put a service query function to do again. ”

Hearing your leader said so, you immediately relieved: "Then you modify the Utility.getonlineplayercount () is good, should not I what matter?" ”

"... It was supposed to be like this ... However, utility and Serverfirst these two classes have been hit into the jar bag, can not be modified ah ... "Your leader is a little awkward.

What This is not the pit father, do I have to change the interface? "You are already in tears."

"This is not necessary, in this case you can use the adapter mode, this mode is to solve the problem of incompatibility between the interface appears." ”

> In fact, the use of adapter mode is very simple, the core idea is as long as the two incompatible interface can be normal docking on the line. In the above code, Xmlbuilder uses the Playercount interface to assemble the XML, and Serverfirst does not implement the Playercount interface. At this point, an adapter class is needed to bridge the Xmlbuilder and Serverfirst, and there is no doubt that ServerOne will act as the role of the adapter class. Modify the code for the ServerOne as follows:

public class serverone implements playercount {             private ServerFirst mServerFirst;             public serverone ()  {           mserverfirst = new serverfirst ();       }          @Override       public  String getservername ()  {          return  "one service" ;      }         @Override        public int getplayercount ()  {           return mserverfirst.getonlineplayercount ();      }     }

This through the serverone of the adaptation, Xmlbuilder and Serverfirst between the successful completion of docking! We don't even have to know the Serverfirst class when we use it, just create an instance of ServerOne as usual.

It is important to note that the adapter pattern is not the kind of pattern that makes the architecture more reasonable, but more often it acts as a firefighter and helps solve the problem of interface mismatches due to unreasonable design of the previous architecture. A better approach is to try to think about what might happen later in the design, and don't learn from your leader on this issue.

Adapter: Transforms the interface of a class into another interface that the customer wants. The adapter mode makes it possible for those classes that would otherwise not work together because of incompatible interfaces to work together.


My supplementary :

The writing of the original author is still fine. Not like me, haha, rubbish to cry.

But the author is always wrong about the order of thinking (or the emphasis). You listen to me for your analysis.


First talk about the topic: (First of all, the author good place)

The last sentence of the author also confirms the essence of adapter: The current offer cannot meet the needs of the customer (i.e. the caller), then the existing service must be packaged or adapted before it can be called.


In the example above, the author retains an instance of the original interface in the adapter class, that is, (essentially) calling the entity that is the wrapped class (here, Serverfirst).

Private Serverfirst Mserverfirst;

(You will see Serverfirst and utility as functional class, functional interface, convenient for you to understand, read the following analysis you will understand)

preserving an instance is a way to implement adapter ------------according to the original author, it is because the interface is incompatible, the classes that cannot work together can work together (although the sentence is right, but it is not well understood), That is, utility and Xmlbuilder can work together (skip this paragraph without understanding, and look at the analysis below). However, this may be another way of saying that if the original service, such as the basic service OK, just want to do on the original basis for expansion or transformation, you can also use this adaptation mode, because what? Because I got the mserverfirst, in the adapter class how to use, add what, is my decision, the client that edge is directly looking for my adapter, not to find a functional interface (such as the utility in this example) what. Look at the code, you get it.

@Override public int Getplayercount () {return Mserverfirst.getonlineplayercount () & UTILITY.GETONLINEPL      Ayercount (); }

This is an example of a basic service upgrade as described above (the method body I call function interface without restrictions, can be upgraded, can be modified)


With regard to the order of thought and the focus, you listen to my understanding.

Then I will ask first, who is the above example, who is the adapter class?

Also see what Yo, ServerOne is adapter class AH.


In the original, there is a sentence:

Xmlbuilder.buildxml (New Serverthree ());

is actually

Xmlbuilder.buildxml (Playercount retuslt);

Our goal is to get 1 people online.

and overbearing Client Client Xmlbuilder, it only playcount this interface,

The other, how to achieve the purpose of it regardless.

OK, the problem arises, the actual implementation of the interface of the function, whether it is the original utility or later upgrade (changed) Serverfirst, and the existing interface Playercount is not compatible AH. (available, not required, and of course it needs to be adapted immediately)

What the hell?

Appeared, the Playercount Interface and utility Interface (Serverfirst) of the adaptation class ServerOne, or the expression: the utility interface to the packaging into ServerOne.

Can't use utility or serverfirst, not to use ServerOne?

I let ServerOne implement Playercount interface, you do not let use? Oh, this solves the problem, I use the Playercount interface (actually its implementation class ServerOne) and no use (no direct use) Utility, overbearing client also did not complete.


So, you see clearly, in fact the focus of the problem (the focus of adaptation), not the utility interface upgrade to the Serverfirst interface, but in playercount and utility such a practical interface between the adaptation.


In conclusion, let me draw a picture for you:

It turned out to be such a relationship:

After not getting through, later became a relationship: (Drawing tools unfamiliar, first endure it)


(Think about the DC and AC power is good, do not say, today can not practice piano, good sleepy)



Java design mode--Adapter (Adapter)

Related Article

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.