Adapter Pattern)

Source: Internet
Author: User

Before the official start, let's first think about several issues:

  • If the existing new project can use a large amount of legacy code from the old project, do you plan to finish the new project from the beginning or understand the module functions and interfaces of the old project?
  • If you have learned about the legacy code and find that several important functional module interfaces are different (because they may come from multiple old projects) and cannot be reused directly, are you planning to stop using the legacy code?
  • If you do not want to give up (this should be correct, after all, the correctness of the legacy code is verified by practice), can you only rewrite the remaining n-1 interface, even rewrite all N interfaces?
  • If this is not done, is there any simple method?

1. What is the adapter mode?

First, we need to know what the adapter is. Well, I have heard of the laptop power adapter?

It can convert the v ac power to the 15 v dc power required by the notebook

It's amazing that a small power adapter solves the problem of mismatch between household power and notebook power.

Have you found anything?

Yes, we didn't change the household power (change it to 15 v dc) or the notebook (change it to v ac), but we did solve this problem.

-------

Adapter mode-design mode used to implement conversion between different interfaces

Ii. Example

Suppose we have two encapsulated functional modules, but they need different parameters (although the parameters are essentially the same object)

For example, our module A (Text check module) is like this:

Package adapterpattern;/*** @ author ayqy * Text check module (similar to "spelling and syntax check" in msoffice word) */public class textcheckmodule {formattext text; public textcheckmodule (formattext text) {This. TEXT = text;}/** omit many specific check operations .. */}

The entry to module A requires a formattext parameter, which is defined as follows:

Package adapterpattern;/*** @ author ayqy * defines the formatted text */public interface formattext {string text = NULL; /*** @ return the number of logical lines in the text */public abstract int getlinenumber (); /*** @ Param index row number * @ return content of the index row */public abstract string Getline (INT index);/** omit other useful methods */}

There is also Module B (text display module), which is like this:

Package adapterpattern;/*** @ author ayqy * text display module */public class textprintmodule {defaulttext text; Public textprintmodule (defaulttext text) {This. TEXT = text;}/** omitted many display-related operations **/}

Defaulttext required for Module B entry:

Package adapterpattern;/*** @ author ayqy * defines the default text */public interface defaulttext {string text = NULL; /*** @ return the number of logical lines in the text */public abstract int getlinecount (); /*** @ Param index row number * @ return content of the index row */public abstract string getlinecontent (INT index);/** omit other useful methods */}

Our new project requires a Text Processing Program (like msoffice word). We need to call module A to implement the text check function, and Module B to implement the text display function.

However, the problem is that the interfaces of the two modules do not match, so that we cannot reuse the ready-made a and B directly ..

In this case, we only have two options:

  1. Modify formattext (or defaulttext) to meet defaulttext (or formattext). You also need to modify the internal implementation of A (or B ).
  2. Define the third interface mytext, modify a and B, and let them take mytext as the parameter, in order to unify the interface

Of course, we may be more inclined to be the first type. After all, there are relatively few modifications required. However, even so, the workload is still large. We need to open the encapsulation of A and understand its internal implementation, and modify the details of the method call.

-------

In fact, we have a better choice-define an adapter to convert formattext to defaulttext (or vice versa ):

Package adapterpattern;/*** @ author ayqy * defines the default text adapter */public class defaulttextadapter implements defaulttext {formattext = NULL; // source object/*** @ Param text the source text object to be converted */Public defaulttextadapter (formattext) {This. formattext = formattext ;}@ overridepublic int getlinecount () {int linenumber; linenumber = formattext. getlinenumber ();/** add additional Conversion Processing here **/return linenumber;} @ overridepublic string getlinecontent (INT index) {string line; line = formattext. getline (INDEX);/** add additional Conversion Processing here **/return line ;}}

Our practice is actually quite simple:

  1. Define the adapter to implement the Target Interface
  2. Obtain and retain the source interface object
  3. Implement each method in the Target Interface (call the method of the source interface object in the method body and add additional processing to implement conversion)

What should I do if the adapter is ready? You may wish to implement a test class to test it:

Package adapterpattern;/*** @ author ayqy * test interface adapter */public class test implements formattext {public static void main (string [] ARGs) {// create the source interface object formattext text = new test (); // create a text check module object textcheckmodule TCM = new textcheckmodule (text ); /* Call TCM for text check * // create an adapter object and convert the source interface object to the Target Interface object. defatexttextadapter textadapter = new defaulttextadapter (text ); // use the adapter to create a text display module object textprintmodule TPM = new textprintmodule (Tex Tadapter);/* Call TCM to display text */}/* ignore the lazy section below .. * // @ Overridepublic int getlinenumber () {// todo auto-generated method stubreturn 0 ;}@ overridepublic string Getline (INT index) {// todo auto-generated method stubreturn NULL ;}}

(P.s. Forgive me for my laziness. Who makes formattext an interface ..)

Of course, test does not have any running results, but compilation is enough to indicate that our conversion is correct ..

-------

In fact, we ignore a very important issue. In this example, the methods of the source interface and the Target Interface correspond, in other words: methods defined in the source interface have similar methods in the target interface.

Of course, there are very few such cases, and there are usually non-corresponding methods (the source interface contains methods not defined by the target interface, or the opposite)

In this case, we have two options:

  • Throw an exception, but you should make a detailed description in the comment or document, as shown in the following code:
Throw new unsupportedoperationexception (); // The source interface does not support this operation
  • Complete an empty implementation, such as return false, 0, null, etc.

The specific choice depends on the specific scenario, each of which has its own advantages and cannot be generalized.

3. Another adapter Implementation Method

In this example, we use the method of "holding the source interface object and implementing the Target Interface" to implement the adapter. In fact, there is another method-Multi-inheritance (or implementation of multiple interfaces)

If an adapter class implements both the interface and the B interface, there is no doubt that the adapter object belongs to both A and B (the principle of multi-inheritance is similar ..)

Although JAVA does not support multi-inheritance, in a language environment that supports multi-inheritance, we should think of this implementation method and decide whether to use multi-inheritance to implement the adapter based on the actual situation.

Iv. Summary

When we hold a two-hole plug and a three-hole plug at the same time, we are always used to wring the plug core into an eight-shaped shape. Why not buy an adapter?

  • There is no need to damage the plug or plug (sometimes code modifications are indeed destructive, so we can avoid modification and damage)
  • More importantly, we can lend the purchased adapter to our friends (reusable)

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.