The principle behind the small example-detailed explanation of the adapter Mode

Source: Internet
Author: User
ArticleDirectory
    • Misuse reason
Last issue review

As mentioned above, a user has taken the industry standard switch (a standard standardswitcher, which relies on the istandardswitchable interface to work, but currently our lamp does not support this interface) and appears in front of me, he shouted that his "Standard switch" should be able to turn on our lights. Well, this requirement is reasonable and should be supported. But the damn thing is, why didn't we know the standard as early as possible? In this way, you do not need to spend time and manpower defining this interface, and now it is not so tangled. Like the previous one, the story-telling and evolution solutions are used to analyze the ideas behind them.

This will mainly explain the adapter mode. gof explains what this mode is, how it is used, and where it is used. I want to explain what the main points of the adapter mode are, how to extend the adapter mode, and how to misuse the adapter mode. By the way, I understand object-oriented design.

Two solutions

Now there are two options.

    1. Let our lights support standard switches directly. That is, implement the istandardswitchable interface for the lamp.

      • Benefits: low cost and elegant implementation methods.

      • Disadvantage: It is equivalent to giving up the user who has bought our lamp and wants to use the standard switch.

    2. Do not change the current light so that the standard switch can turn on our light. We cannot change the standard interface or the lamp. Fortunately, there is a saying in the computer industry that "adding a layer can solve all problems ". This reminds me of the Power Interface Converter that I bought for a foreign electrical appliance. Now, we need something similar to the lamp.

      • Benefit: supports all lights.

      • Disadvantage: this is a gift that will reduce our profits.

The first solution is simple, that is, let light implement multiple interfaces. The graph is not given.

Now, the second solution is analyzed. The standard interface depends on the istandardswitchable interface, so we must have a class to implement it and complete the required function-the operation lamp. I have also learned the design model. This problem can be clearly explained using the adapter mode.

You can easily draw related class diagrams.

Figure 1 solution for enabling the lamp to support the istandardswitchable Interface

 

The correspondingCodeIt will look like this:

Public InterfaceIstandardswitchable
 
{
 
VoidTurnon ();
 
VoidTurnoff ();
 
}
 
 
 
Public ClassSwitcheradapter: istandardswitchable
 
{
 
PublicLight switchee {Get; set ;}
 
 
 
Public VoidTurnon ()
 
{
 
Switchee. turnon ();
 
}
 
 
Public VoidTurnoff ()
 
{
 
Switchee. turnoff ();
 
}
 
}

Code 1

Job done. Light supports new interfaces through switcheradapter, which is a model of the application adapter mode. (Well, this is indeed a counterargument, but do you guess why this adapter does not belong to the adapter mode ?)

"I told you so much about the last time, but I didn't think you were so confused. Think about it yourself !" Looking at the design of my UML diagram, Guru seems a little angry.

Last time? I calmed down and thought back to the previous content and current problems. The dip mentioned in the previous review is not dependent on implementation, but on abstraction. Think about the current demand. We have lights and radios. If you want to enable a standard radio switch, isn't it necessary to implement a radioadapter? This apparently violates OCP.

The requirement is to "enable the lamp to support standard switch by adding a layer", but it does not mean that the lamp must be used for this layer. To make this adapter more generic, the adapter should be dependent on the iswitchable interface. As shown below.

Figure 2 adapter Mode

 

The difference from code 1 is that the type of the switchee attribute in the switcheradapter is changed to iswitchable. The code will not be pasted. The principle is the dip mentioned in the previous article.

In fact, anyone can think of it quietly. However, when an urgent demand comes, it is easier for people to put the work done first, in this way, we ignored the design rigor and forgot to refactor it later, so bad smell was born like this. Of course, we all know this.

Object-oriented design is not a simulation of reality

(This is an episode. Because this argument is too large, I feel that I am not writing, but I am sorry for my love style. I am sorry for your comments. If you think the problem is too far away, you can take a look at the Section .)

But (the point is coming), why is it more likely that the intuitive design made when the stress is tight? When people are nervous, they are easy to feel by their feelings. When designing with intuition, the Metropolis is based on the real world. However, good object-oriented design cannot rely solely on the real world.In fact, the design in Figure 1 intuitively meets the needs and people's perception of the world. But it is notGoodObject-Oriented Design. Figure 2 is a relatively good design, but figure 2 is obviously not as intuitive as Figure 1, so easy to understand, so in line with the worldReal status.

The difference between figure 2 and Figure 1 lies in who the adapter depends on, and the adapter depends on the iswitchable interface, not to simulate the world more realistically, purely for understanding coupling (or for dependency abstraction ). However, in the real world, there is no concept of coupling. Decoupling is a concept introduced to ensure design flexibility.

In reality, dependencies between things are specific.,Abstract is introduced for reuse and flexibility. objective reality is not abstract. Abstraction depends on how you view objective things.For example, in the view of zoologists, there is a IS-A relationship between humans and animals; but if you are developing an MMORPG game, people (NPC and Avatar) and animals (usually monsters) should not have a IS-A relationship. Different designs can be obtained from different angles of observation. There is no right or wrong between these designs, except whether they meet the requirements.

Therefore, in some cases, it is one-sided to interpret the object-oriented design process as a simulation of the real world. If the system is designed just in the real world, the resulting design may be rigid, as shown in figure 1. (Some people may want to say that I misinterpret what people mean, but I want to say that what you write is clearly intended to misunderstand people, at least it is easy to guide people to misunderstand. It is easy to be misunderstood, that is, there is a problem. There is nothing to argue about .)

However, this does not mean that the design should be fully abstracted. The advantage of simulating the real world is that the Code is easy to understand. However, if all are abstracted into 2, all are abstracted into an interface, all of them depend on abstraction, and the code's readability is obviously reduced. So,A good object-oriented design will truly simulate the trade-off between reality and abstract reality.If you have read some open-source frameworks with similar functions but different implementations, you may find that they are easy to understand and some are hard to understand. The root cause is that they have different levels of abstraction or their degree of abstraction. Abstract is too high, and flexibility may be improved, but it is not necessarily a good thing.Excessive design is caused by the high abstraction of reality, resulting in poor readability and poor maintenance.If the problem persists, the problem is first solved.

The above example may still be unconvincing. Let me give you another one. Someone replied in the previous article that,

"The switch also contains a switch interface, which is a strange method.

In my opinion, the light should have a switch ".

I would like to thank this friend for ignoring his ideas. As mentioned by him, I realized that this is also a common problem in the design process. This design is a realistic design. But it is not a feasible class design. If you write code in this solution, you will find many problems. I have replied to the cause.

To sum up, remember what you need to do when Designing object-oriented systems? Do not confuse the real world with audio and video.Object-oriented design aims to achieve requirements in a reusable and flexible manner. It abstracts reality rather than simulates reality. abstract results may not exist in reality.

Key to adapter Mode

The most important requirement of the adapter mode is that the adapter isTwo interfaces with similar functions. If the object to be adapted is a specific class, in most cases, the adapter will not only bring benefits, but will only increase the maintenance cost, as mentioned above, if a new class appears, you must add an adapter at the same time.

(If you have not said that you have seen many "adaption" specific classes, you are right, but it is called proxy, not adapter, and it does not solve the same problem either, in most cases, the proxy can be automatically generated, so you do not need to worry about adding a class, you need to implement a corresponding proxy on your own. You can use the figure below to compare it from agile software development.)

Figure 3 proxy Mode

 

This is not the meaning of the dead adapter mode. This mode will not be misused only after you understand the goals and applicability of the adapter. I have seen many people who have a good understanding or good English. When I see the word adapter as a model, I naturally think that I am "aware" of the usage of this model (after all, this model is indeed not complex ), and "use. The example of ratio 1 is one of the most common misuse.

This is not a term for death. One of the benefits of naming a pattern is to make it easier for both people who understand the pattern to communicate.The schema name is not a simple class relationship diagram, but a strategy for locating the type of the problem to be solved and solving the problem.

Adapter, indicating that the interface does not match.

Proxy, indicating that the problem is the entanglement between the subject logic and the additional logic (persistence, network transmission, etc.

If the term is used incorrectly, it may lead to unnecessary misunderstandings.

If you feel that there is no need to commit, the following "Generalized adapter mode" may be more suitable for you.

Generalized adapter Mode

In this year, everything seems to have to be divided into narrow and broad sense. I personally dislike this, because the existence of narrow and wide points is a fuzzy concept. This leads to people who encounter problems during communication, and often think about whether the other party is talking about the problem in a broad or narrow sense, rather than focusing on the problem itself. This is like making excuses or looking back at yourself and your other party. It may be because everyone wants to leave a path for themselves. This is so popular. Appendix:

"Well? No, it shouldn't be XXXX.?"

"Well, I'm talking about XXXX in a broad sense.."

"Oh. (Shit!)"

Every people's learning model always has their own understanding and abstraction. When the angle of understanding is different, the connotation of the adapter pattern is extended to different places. As a result, different people have different definitions of the generalized adapter.

For example, in agile software development, the concept of adapter is extended from the logic relationship: using a specific class to achieve targeted distribution of method calls (I have summarized it myself, this is not the case in the original article ). In terms of concept, the adapter mode can be used to adapt to a specific class. Because the concept of this extension has actually exceeded the definition of the original gof. Obviously, this cannot be said to be wrong. You may even think that this person is really high and can abstract and expand the design pattern.

But the problem is,Different people have different directions for extending the same concept.. Do you think adapter and delegate/event have any similarities? I believe more people will think that the observer mode is more similar to delegate/event. Many people and books have said that the delegate/event mechanism of c # is a specific implementation of the observer mode. If you say that delegation is an adapter during the interview, you may pass the interview directly. This happened indeed.

However, if you go to page 112nd of "Pro objective-C design pattern for iOS", this is the true description of adapter.

"The delegation pattern was once one of the inspirations for cataloging the adapter

Pattern in the "Gang of Four" book."

If you are afraid that I will take it out of context, you can check it by yourself.

This person defines the combination of classes with similar structures and interactions as adapter based on the relationship between classes. Did you say his understanding is wrong? I can only say: "In a narrow sense, it is wrong. In a broad sense, it is right ." However, this is one of the best answers in the world.

The interviewer, as described in the blog above, is clearly the victim of the broad and narrow sense-he is talking about the adapter in the broad sense, but the interviewer wants to hear the adapter in the narrow sense. (As described later, the interviewer is also half a bottle of vinegar. When asked about delegate, the interviewer will actually ask about Asynchronization, so I have to doubt if he thinks the event is triggered asynchronously .)

It has a unique understanding of the adapter. It can understand the adapter, observer, delegation, and proxy in a unified manner and even more Nb. However, in most cases, the more unique the insights are, the more likely it will bring obstacles to face-to-face communication. These unique insights are useful in the process of personal epiphany and are well written into the book. After all, readers can appreciate them carefully and help them think about problems from different perspectives; however, I want to attach a force to face-to-face communication such as interviews, and then I can be eloquent. I am afraid that I will only draw tigers rather than reverse dogs.

Misuse of adapter Mode

When learning history, we often see words like "left" and "right", which means they are not on the correct path. This word is used very vividly, and is always extreme. Misuse of models. One of the Common misuse is also extreme.

In the adapter mode in Figure 2, the standard switch interface is successfully adapted to our interface. Now we have a logic. Both iswitchable and istandardswitchable interfaces define switches. We use the adapter mode to enable the istandardswitchable switch to turn on our lights.

So our previous design:

Figure 4. switched on/off solution (Abstract server) proposed in the first round)

 

Should this be the case?

Figure 5. Try to use the adapter mode to implement dip

 

This design is more abstract and less coupled than the original design scheme. Light can work without relying on the iswitchable interface, so we can confidently say that, we can make all classes support the iswitchable interface!

This idea is full, but the reality is very skinny. If you have carefully read the previous content, you should already know the reason for the bad solution.

The world is very subtle. Agile Software Development (p370) does call Figure 5 the adapter model, but you should understand that it is a broad adapter model. It does not mean that the adapter for a specific class must be misused. If there is no violation of OCP, It is not misuse. If the light is a utility class, it is not misuse.

(If you want to spray the adapter mode, there are two types, one is class-based and the other is object-based. You 'd better go back to the furnace of the adapter concept first, we are not talking about one thing at all .)

Misuse reason

I have summarized three reasons for this misuse (these reasons may lead to misuse of various forms rather than the adapter mode ):

  1. And so on.As shown above, it is feasible to adapt to istandardswitchable. It is also possible to directly launch an interface that adapts to iswitchable. After all, this is the same function. However, this is not the case.

  2. The idea of trying to solve all problems in the same way or creating something that works for everything.I intuitively want to use the second law of thermodynamic to refute this idea (similar to work forever), but "no silver bullet" may be more appropriate. But some people, especially those with a higher level, are more likely to fall into this quagmire. Maybe they think it is too sorry for not creating something Nb. Of course, this idea is good, but we also need to emphasize methods. It is impossible to take a hammer to see what is a nail. Refer to ten good programming ideas.The first is independent thinking.The idea of trying to cope with all design problems through learning various models is not necessary. Another thing that impressed me a lot is the use of Google. I suggest you take a look.

  3. I do not have a thorough understanding of the design principles and patterns.If you really understand the intent and applicability of the adapter mode. It will not make such a mistake. However, it is a pity that there are too many temptations in this world, even where Wikipedia seems very authoritative, it is misleading others (Therefore, think and judge by yourself.). Wikipedia explained dip as follows: "applying the Dependency inversion principle can also be seen as applying the adapter pattern, I. e. "the Dependency inversion principle can be regarded as the application adapter mode ". Oops... If the adapter mode is used, it is indeed dip, but the adapter is not used to achieve the dip goal. Although the adapter mode is dip, if it is used for real dip, the effect is very bad, it brings about more problems. I guess the author's intention is to express that the adapter mode itself complies with the dip principle. That's right. But I believe one vote will study the adapter mode and plan to use it for dip. (Some people think that I am too arrogant. I just want to clarify the problem so that more people can misunderstand it .)

    The lack of experience here may not be a problem of insufficient working years. It is more likely to be a problem of attitude, or take the adapter mode for granted and feel that you have almost understood it literally, either you want to make the so-called "active" for the adapter mode, and the result is a radical adventurous mistake.

Next Forecast

When our lights are sold well, there will be more users and more demands. In this way, two users are coming. One requirement is that I use two switches to control the same lamp (one bedside and one corridor). The other requirement is that the user often gets up and down at night, I want to use a switch to control all the lights in the room (it seems that this user is not bad money ).

So what design should we do to address these needs?

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.