Design mode-Adapter mode "Adapter pattern"

Source: Internet
Author: User

Statement: This article from the network books collated, not original.

Adapter mode, this mode is also very simple, your notebook on the outside of the black box is an adapter, generally you can use in China, can be used in Japan, although the two countries, the supply voltage is different, China is 220V, Japan is 110V, but this adapter can convert these different voltages to the 36V voltage to make sure your laptop is working properly, is that what we're introducing to this adapter pattern in design mode? Yes, the same effect, two different interfaces, there are different implementations, but one day suddenly God commands you to convert the B interface to a interface, what to do? Inheritance, can solve, but more silly, but also against the OCP principle, how to do? Fortunately we also have adapter mode.

The general class diagram of the adapter is like this:

Target is a class (interface), Adaptee is an interface, through the Adapter to wrap the adaptee into a subclass of Target (Implementation Class), notice here with a noun packaging (Wrapper), which is actually called the packaging mode (Wrapper) , but the packaging mode is not known, but also includes the future to talk about the decorative mode. I say one of their own experience, so that everyone can more easily understand the adapter mode, otherwise pure talk technology is too boring, technology can also have entertainment.

I brought a project in 2004, to do a human resources management, the project is a project initiated by our head office, the company has a total of 700 supposedly people, including subsidiaries, this project is relatively simple, divided into three modules: personnel information management, compensation management, job management, One of the personnel management this piece is used in the adapter mode, what is going on? At the time of development, it was clear that the object of the simple management of personnel information was all the information of all employees, and then we designed a class diagram like this:

is still relatively simple, there is an object UserInfo store all the information of the user (there are many subclasses on the actual system, not much to say), that is Bo (business object), this UserInfo object, used in many places in the system, you can view your information, can also be modified, of course, this object is a setter method, we do not use here to hide.

This project was put into production at the end of 04, running until the end of 05 is still relatively stable, the middle of tinkering is also very normal, the end of 05 is not known that the wind blew, many companies began to use the way to recruit staff, our company is no exception, from a human resources company borrowed a large number of low-tech, Low-wage personnel, assigned to the various subsidiaries, a total of nearly No. 200 people, and then find our department boss negotiations, said to add a function to borrow staff management, the eldest brother a look at money to earn Ah, a pat thigh, do!

I brought people past research, not so simple, human resources companies have their own personnel management system, our company needs to transfer the personnel information we use to our system, the transmission between the system using RMI (remote Method invocation, long-distance object call) way, But there's a problem. The human resources Company's personnel objects are not the same as the objects of our system, their object is this:

Personnel resources Company is to divide people's information into three parts: basic information, office information and personal family information, and all put in the hashmap, such as the name of the person put into the baseinfo information, home address put in Homeinfo, which I do not say that their system design is not good, The problem is that our systems have to interact with their systems. Using the adapter mode, the class diagram is as follows:

You might ask, how do you use these two objects that are not in one system? Simple! RMI has helped us do this thing, as long as there is an interface, you can use the remote object as a local object, the people have time to look at the RMI documentation, not much to say. Through the adapter, the Outeruser disguised as a Iuserinfo object in our system, so that our system basically does not have to modify what program, all the staff query, call with the local kind, said the parched, then we look at the specific code implementation:

First look at the Iuserinfo.java code:

 Public InterfaceIuserinfo {//Get the name of the user     PublicStringGetUserName();//Get home address     PublicStringgethomeaddress();//Mobile phone number, this is too important, mobile phone flooding ah     PublicStringGetmobilenumber();//Office phone, general-type landline     PublicStringGetofficetelnumber();//What is this person's position ?     PublicStringgetjobposition();//Get home phone, this is a bit wicked, I don't like to play home phone talk work     PublicStringGethometelnumber(); }

Then look at the implementation class for this interface:

 Public  class UserInfo implements iuserinfo {     / * * Get a home address, a subordinate gift can also find a place * *      PublicStringgethomeaddress() {System.out.println ("This is the employee's home address ....");return NULL; }/ * Get home phone number * *      PublicStringGethometelnumber() {System.out.println ("The staff was very friendly and the room was very nice.");return NULL; }/ * Employee position, Department Manager or soldier * *      PublicStringgetjobposition() {System.out.println ("This man's position is boss ...");return NULL; }/ * * Mobile number * *      PublicStringGetmobilenumber() {System.out.println ("This person's cell phone number is 0000 ...");return NULL; }/* Office phone, the best when irritability (flurried ⌒ G to kick off the phone line, I often do so, it is good for others * *      PublicStringGetofficetelnumber() {System.out.println ("The Office phone is ....");return NULL; }/ * Name, this old important * *      PublicStringGetUserName() {System.out.println ("Name is ...");return NULL; } }

Some people may ask, why do you want to set the phone number, cell phone number to the String type, rather than the type of int, you feel it? aside, this should definitely be a String type, including database should be varchar type, mobile phone number has PHS with area code, such as 02100001, how do you use numbers to express? Some people have to add 0086 before the mobile phone number and then save, such as our company's India, the third is this, like the mobile phone number in the first 0086 to save, hehe, I was thinking about what to say, wordy point. Keep looking at our code below to see how our system application calls UserInfo information:

publicclass App {     publicstaticvoidmain(String[] args) {         //没有与外系统连接的时候,是这样写的         new UserInfo();         //从数据库中查到101个         for(int i=0;i<101;i++){             youngGirl.getMobileNumber();         }     

101 UserInfo objects are generated from the database and printed directly. Then how to deal with the personnel information of the external system? Here is the source code for Iouteruser.java:

publicinterface IOuterUser {     //基本信息,比如名称,性别,手机号码了等     publicgetUserBaseInfo();     //工作区域信息     publicgetUserOfficeInfo();     //用户的家庭信息     publicgetUserHomeInfo

Let's look at the specific implementation class for the user information of the External system:

 Public  class outeruser implements iouteruser {     / * User's basic information */      PublicMapGetuserbaseinfo() {HashMap Baseinfomap =NewHashMap (); Baseinfomap.put ("UserName","This employee is called dyed villain ..."); Baseinfomap.put ("Mobilenumber","This employee phone is ...");returnBaseinfomap; }/ * * Employee's family information * *      PublicMapGetuserhomeinfo() {HashMap Homeinfo =NewHashMap (); Homeinfo.put ("Hometelnumbner","The staff was very friendly and the room was very nice."); Homeinfo.put ("HomeAddress","The family address of the employee is ....");returnHomeinfo; }/ * * Employee's job information, such as position, etc. * /      PublicMapGetuserofficeinfo() {HashMap Officeinfo =NewHashMap (); Officeinfo.put ("Jobposition","This man's position is boss ..."); Officeinfo.put ("Officetelnumber","The staff is very friendly.");returnOfficeinfo; } }

How to package the user information of the external system into our company's personnel information? Look at the following Outeruserinfo class source code, which is our adapter:

 Public  class outeruserinfo extends outeruser implements Iuserinfo  {     PrivateMap Baseinfo =Super. Getuserbaseinfo ();//basic information of employees    PrivateMap Homeinfo =Super. Getuserhomeinfo ();//Employee's family information    PrivateMap Officeinfo =Super. Getuserofficeinfo ();//Job Information    / * * Home Address * *      PublicStringgethomeaddress() {String homeaddress = (string) This. Homeinfo.get ("HomeAddress"); System.out.println (homeaddress);returnhomeaddress; }/ * * Home Phone number * *      PublicStringGethometelnumber() {String hometelnumber = (string) This. Homeinfo.get ("Hometelnumber"); System.out.println (Hometelnumber);returnHometelnumber; }/ * Job Information * *      PublicStringgetjobposition() {String jobposition = (string) This. Officeinfo.get ("Jobposition"); System.out.println (jobposition);returnJobposition; }/ * * Mobile number * *      PublicStringGetmobilenumber() {String mobilenumber = (string) This. Baseinfo.get ("Mobilenumber"); System.out.println (Mobilenumber);returnMobilenumber; }/ * * Office phone * *      PublicStringGetofficetelnumber() {String officetelnumber = (string) This. Officeinfo.get ("Officetelnumber"); System.out.println (Officetelnumber);returnOfficetelnumber; }/ * * Employee's name * /      PublicStringGetUserName() {String userName = (string) This. Baseinfo.get ("UserName"); System.out.println (UserName);returnUserName; } }

Did you see that? There are a lot of coercion type conversion, that is (String) This thing, if the use of generics, it can completely avoid the transformation, this lesson too much to stop talking, next time to talk about. The function of this adapter is to do the interface conversion, then we'll see how our business is called:

public   Class  App {public  static  void  main  (string[] args) {//not with the external system        Connection, the  //iuserinfo younggirl = new UserInfo ();         //boss a think wrong, rabbits do not eat hualaopo, or to find staff of human resources better   Iuserinfo younggirl = new  outeruserinfo ();        //we only modified this sentence good         //a database of 101  for  (int  i=0 ; I<101         ; i++) {younggirl.getmobilenumber (); }    } } 

You see, the use of the adapter mode only modified a sentence, the other business logic is not modified to solve the problem of the system docking, and in our actual system just added a business class inheritance, we can check the company's staff information, can also check the staff information of human resources company, as little as possible to modify, The problem was resolved by an extension.

Adapter mode is divided into class adapters and object adapters, this is not a big difference, the above example is the class adapter, what is the object adapter look like? The class diagram of the object adapter looks like this:

Did you see that? And the top of the class diagram on an arrow of the graphic differences, one is the inheritance, one is related, so many differences, as long as the above program slightly modified to become the class adapter, this people think about it, simple very.

Adapter mode is not suitable for use in the system design phase, no system analyst will consider using adapter mode when making detailed settings, the main scenario used in this mode is to extend the application, just like the example above, the system expands, When you do not conform to the original design, consider using the adapter mode to reduce the risk of code modification.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Design mode-Adapter mode "Adapter pattern"

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.