Chapter 4 adapter mode [adapter pattern]

Source: Internet
Author: User

<24 design patterns and six design principles>

Well, please be quiet. Do not wake the Students Sleeping in the front row. You need to understand each other. I will talk about the adapter mode today.
The black box on your laptop is an adapter. It can be used in China and Japan,
Although the power supply voltage in two countries is different, China is 220 V, and Japan is 110 V, but this adapter can convert these different voltages
If you need a 36 V voltage to ensure that your notebook can run properly, do you need to introduce this adapter mode in the design mode?
What does that mean? Yes, the same effect. Two different interfaces have different implementations, but one day, God commands you to set the B Interface
What should I do if I convert it to interface? Inheritance can be solved, but it is silly and violates the OCP principle. What should I do? Fortunately, we still have
Accept mode.
The generic class diagram of the adapter is like this:

First, I declare that this is not what I drew. This is taken from the Help File of Rational Rose, and this class chart is easy to understand,
Target is a class (Interface), adaptee is an interface, and adaptee is encapsulated into a subclass of target through the adapter (
Class). Note that wrapper is used here. In fact, this mode is also called wrapper,
But it also includes the decoration mode to be discussed later. Let me talk about my own experience, so that you can better understand this
Else, the technology is too boring, and the technology can be entertaining.


In 2004, I brought a project for Human Resource Management. This project was initiated by our company.
There are more than 700 employees, including subsidiaries. This project is relatively simple and can be divided into three modules: personnel information management, compensation management, and positions.
Management: The Personnel Management module uses the adapter mode. What is the problem? At that time, it was clearly stated during the Development: simplified management of personnel information
The object is all the information of all employees, and then we design a class diagram as follows:

 

 

Link, and I am also opposed to using rich business object. Here we talk about two terms: Anemia object and congestion object.
Objects. These two terms are very simple. In the domain model, they are called the anemia domain model and the congestion domain model. What is the difference? In
The object that does not store the state of the object and the relationship between the object is called the anemia object. Rising to the domain model is the anemia domain model.
The model of the relationship between object state and object is the congestion domain model. Is it too technical? It doesn't matter if you don't understand it. It's all dummies.
Things are special terms. After writing this book, I will turn to the articles on models in this field to reveal the specific terms in the domain model,
This is definitely an accumulation of proprietary terms. Let's continue to talk about the adapter mode. This userinfo object has many
For local use, you can view your own information or make modifications. Of course, this object has a setter method, and we can't use it here.
Hidden.


This project was put into operation at the end of, and was stable at the End of. It was also normal for intermediate repairs and supplements.
I don't know what it is. Many companies start to hire people by hiring them, and our company is no exception.
The company borrowed a large number of low-tech and low-wage employees and assigned them to various subsidiaries. There were nearly 200 employees in total. Then we went to our department.
The boss negotiated to add a function to borrow personnel for management. The old freshman looked at him to earn money, shoot his thigh, and did it!

 

It's not that simple. The Human Resources Company has a set of its own personnel management system, and our company needs
The personnel information used is transmitted to our system, and the transmission between systems uses RMI (Remote Method invocation, remote object
But there is a problem that the human resources company's personnel object is different from the object in our system. Their object is like this.
Of:

Personnel Resource companies divide people's information into three parts: basic information, office information and personal and household information, and all of them are stored in hashmap.
For example, if a person's name is put in baseinfo information and the home address is put in homeinfo, it is hard to say that their system is poorly designed,
The problem is that our system needs to interact with their systems. What should we do? Use the adapter mode. The class diagram is as follows:

You may ask how to use these two objects if they are not in the same system? Simple! RMI has helped us with this,
If there is an interface, you can use remote objects as local objects. You can take a look at the RMI document if you have time.
. Use the adapter to disguise outeruser as an iuserinfo object in our system. In this way, our system does not need to be modified.
What programmers and all personnel query and call are similar to those on the local device? Let's look at the specific code implementation below:

First, check the iuserinfo. Java code:

 

Package CN. mjorcen. adapter_pattern.service;/*** @ author cbf4life [email protected] I'm gglad to share my knowledge with you * All. user information object */public interface iuserinfo {// obtain the user name Public String GetUserName (); // obtain the home address public string gethomeaddress (); // mobile phone number, which is too important, mobile phone flooding Public String getmobilenumber (); // office phone number, General landline Public String getofficetelnumber (); // What is the position of this person Public String getjobposition (); // obtain the home phone number. This is a bit of a defect. I do not like to call the home phone to discuss the work Public String gethometelnumber ();}

 

 

Someone may ask why we should set the phone number and mobile phone number to the string type instead of the int type.
What about it? In other words, this is definitely a string type, including databases, but also varchar type. Cell phone numbers include PHS band.
Number, such as 02100001. How do you use a number to represent it? Some people need to add 0086 in front of the mobile phone number before saving, such as our company
This is the case with aosan, India. I like to save it in the first 0086 of the mobile phone number. Haha, I just want to say what I think, so I am a little embarrassed. Continue watching me
The code below shows how our system's application calls the userinfo information:

Package CN. mjorcen. adapter_pattern; import CN. mjorcen. adapter_pattern.service.iuserinfo; import CN. mjorcen. adapter_pattern.service.impl.outeruserinfo;/*** @ author cbf4life [email protected] I'm gglad to share my knowledge with you * All. this is our specific application. For example, the boss needs to check all 20-30 female information */public class app {public static void main (string [] ARGs) {// when there is no external system connection, iuserinfo younggirl = new userinfo () is written in this way; // 101 For (INT I = 0; I <101; I ++) {younggirl. getmobilenumber ();}}}

 

 

Then let's look at the implementation class of this interface:

Package CN. mjorcen. adapter_pattern.service.impl; import CN. mjorcen. adapter_pattern.service.iuserinfo;/*** @ author cbf4life [email protected] I'm gglad to share my knowledge with you * All. */public class userinfo implements iuserinfo {/** get the home address. For gifts from subordinates, you can also find your design mode page 55th */Public String gethomeaddress () {system. out. println ("here is the employee's home address .... "); return NULL;}/** obtain the home phone number */Public String gethometelnumber () {system. out. println ("the employee's home phone number is .... "); return NULL;}/** employee position, department manager or soldier */Public String getjobposition () {system. out. println ("this person's position is boss .... "); return NULL;}/** mobile phone number */Public String getmobilenumber () {system. out. println ("this person's mobile phone number is 0000 .... "); return NULL;}/** office phone number. It is best to" accidentally "kill the phone line when you are bored. I often do this, good for people */Public String getofficetelnumber () {system. out. println ("the office phone number is .... "); return NULL;}/** name, which is always important */Public String GetUserName () {system. out. println ("name is... "); return NULL ;}}

The boss, why is it 101? You should know that 111 represents boys and 101 represents girls.
Yes. A total of 101 userinfo objects are generated from the database and printed directly. Then the external system staff are added.
Information. How can this problem be solved? The source code of iouteruser. Java is as follows:

Package CN. mjorcen. adapter_pattern.service; import Java. util. map;/*** @ author cbf4life [email protected] I'm gglad to share my knowledge with you * All. external System personnel information */@ suppresswarnings ("all") public interface iouteruser {// basic information, such as the name, gender, and mobile phone number. Public map getuserbaseinfo (); // public map getuserofficeinfo (); // public map getuserhomeinfo ();}

 

Let's take a look at the specific implementation classes of user information in external systems:

Package CN. mjorcen. adapter_pattern.service.impl; import Java. util. map; import CN. mjorcen. adapter_pattern.service.iuserinfo;/*** @ author cbf4life [email protected] I'm gglad to share my knowledge with you * All. package outeruser into userinfo */@ suppresswarnings ("all") public class outeruserinfo extends outeruser implements iuserinfo {private map baseinfo = super. getuserbaseinfo (); // basic employee information private map homeinfo = super. getuserhomeinfo (); // the employee's home information private map officeinfo = super. getuserofficeinfo (); // work information/** home address */Public String gethomeaddress () {string homeaddress = (string) This. homeinfo. get ("homeaddress"); system. out. println (homeaddress); Return homeaddress;}/** home phone number */Public String gethometelnumber () {string hometelnumber = (string) This. homeinfo. get ("hometelnumber"); system. out. println (hometelnumber); Return hometelnumber;}/** Job Info */Public String getjobposition () {string jobposition = (string) This. officeinfo. get ("jobposition"); system. out. println (jobposition); Return jobposition;}/** mobile phone number */Public String getmobilenumber () {string mobilenumber = (string) This. baseinfo. get ("mobilenumber"); system. out. println (mobilenumber); Return mobilenumber;}/** your design mode 60th page office phone number */Public String getofficetelnumber () {string officetelnumber = (string) This. officeinfo. get ("officetelnumber"); system. out. println (officetelnumber); Return officetelnumber;}/** employee name */Public String GetUserName () {string username = (string) This. baseinfo. get ("username"); system. out. println (username); Return username ;}}

 

Do you see this? There are a lot of forced type conversions here, that is, (string). If you use generics, you can
To avoid this conversion, I will not talk about this lesson if I have too many questions. I will talk about it again next time. This adapter is used for Interface Conversion,
Then let's take a look at how our business is called:

Package CN. mjorcen. adapter_pattern; import CN. mjorcen. adapter_pattern.service.iuserinfo; import CN. mjorcen. adapter_pattern.service.impl.outeruserinfo;/*** @ author cbf4life [email protected] I'm gglad to share my knowledge with you * All. this is our specific application. For example, the boss needs to check all 20-30 female information */public class app {public static void main (string [] ARGs) {// when there is no connection to the external system, it is written in this way // iuserinfo younggirl = new userinfo (); // if the boss thinks it is wrong, the rabbit will not eat anything, iuserinfo younggirl = new outeruserinfo (); // We only modified this sentence. // we found 101 For (INT I = 0; I <101; I ++) {younggirl. getmobilenumber ();}}}

As you can see, the adapter mode is used to modify only one sentence, and other business logic does not need to be modified to solve the problem of system connection,
In addition, we only add a business class inheritance in our actual system, so that we can check the company's employee information or human resources.
The employee information of the resource company should be modified as little as possible to solve the problem through extension.
The adapter mode is divided into a class adapter and an Object Adapter. This is slightly different. The above example is a class adapter, and the Object Adapter is
What does it look like? The class diagram of the Object Adapter is like this:

 

 

 

 

See? There is a difference between a class chart and an arrow graph above. One is inheritance, and the other is association. There are so many differences. As long as the above program is slightly modified, it becomes a class adapter, this is simple for everyone to think about.

The adapter mode is not suitable for use in the system design phase. No system analyst will consider using the adapter mode for detailed settings. The main scenario of this mode is to expand applications, just like in the example above, the system is extended and the risk of code modification is reduced only when it does not conform to the original design. On the Forum, some netizens suggested that I add advantages and disadvantages of the mode. I do not recommend that you add this mode. You have mastered how to use it first and then want to use it better, and I think you have come to the idea that you want to use these 23 models. There must be a balance between them. Will the advantages and disadvantages of this model be better summarized by yourself?

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.