Java and mode 26-7th-adapter Mode

Source: Internet
Author: User
Document directory
  • Source code
  • Source code
  • Balance between class adapters and object adapters

The adapter mode converts an interface of a class into another interface that the client expects, so that the two classes that cannot work together due to interface mismatch can work together.

Usage of the adapter Mode

  Using electrical appliances as an example, the plug of the laptop is generally three-phase, that is, in addition to the anode and cathode, there is also a ground pole. In some places, the power outlet is only two poles without a ground pole. The power plug of the power outlet does not match the power plug of the laptop so that the laptop cannot be used. At this time, a three-phase to two-phase converter (adapter) can solve this problem, and this is like what this mode does.

Structure of the adapter Mode

The adapter mode hasClass adapter ModeAndObject Adapter ModeTwo different forms.

Class adapter Mode

The adapter mode of the class converts the API of the adaptive class into the API of the target class.

 

As can be seen in, the adaptee class does not have the sampleoperation2 () method, and the client expects this method. To enable the client to use the adaptee class, a class adapter is provided to link the adaptee API with the target class API. The adapter and adaptee are inherited, which determines that the adapter mode is class:

The role involved in the mode is:

Target role:This is the expected interface. Note: The class adapter mode is discussed here, so the target cannot be a class.

Source (adapee) role:The interface to be adapted.

Adapter (adaper) role:The adapter class is the core of this mode. The adapter converts the source interface to the target interface. Obviously, this role cannot be an interface, but must be a specific class.

Source code
Public interface target {/*** this is also the method of source class adaptee */Public void sampleoperation1 (); /*** this is a method not available in the source class adapteee */Public void sampleoperation2 ();}

 

The source code of the target role is provided above. This role is implemented in the form of a Java interface. We can see that this interface declares two methods: sampleoperation1 () and sampleoperation2 (). The source role adaptee is a specific class. It has a sampleoperation1 () method, but there is no sampleoperation2 () method.

public class Adaptee {        public void sampleOperation1(){}}

 

The adapter role adapter extends adaptee and implements the target interface. Since adaptee does not provide the sampleoperation2 () method and the target interface requires this method, the adapter role implements this method.

Public class adapter extends adaptee implements target {/*** because the source class adaptee does not have a method sampleoperation2 () *, the adapter supplements this method */@ override public void sampleoperation2 () {// write related code }}

 

Object Adapter Mode

Like the adapter mode of the class, the Object Adapter mode converts the API of the adapted class into the API of the target class. Unlike the adapter mode of the class, the object's adapter mode is not to connect to the adaptee class by using an inheritance relationship, but to connect to the adaptee class by using a delegation relationship.

As you can see, the adaptee class does not have the sampleoperation2 () method, and the client expects this method. To enable the client to use the adaptee class, a wrapper adapter is required. This packaging class encapsulates an adaptee instance, so that this packaging class can link the adaptee API with the target class API. The adapter and adaptee are delegates, which determines that the adapter mode is object.

Source code
Public interface target {/*** this is also the method of source class adaptee */Public void sampleoperation1 (); /*** this is a method not available in the source class adapteee */Public void sampleoperation2 ();}

 

public class Adaptee {    public void sampleOperation1(){}    }

 

Public class adapter {private adaptee; Public adapter (adaptee) {This. adaptee = adaptee;}/*** method sampleoperation1 * for the source class adaptee. Therefore, the adapter class can be directly delegated. */Public void sampleoperation1 () {This. adaptee. sampleoperation1 ();}/*** the source class adaptee has no sampleoperation2 *. Therefore, this method needs to be supplemented by the adapter class */Public void sampleoperation2 () {// write the relevant code }}

 

Balance between class adapters and object adapters

Class AdapterObject Inheritance is a static definition method.Object AdapterObject combination is a dynamic combination.

For Class adaptersBecause the adapter directly inherits adaptee, the adapter cannot work with the sub-class of adaptee, because the inheritance is a static relationship. After the adapter inherits adaptee, it is impossible to process the sub-classes of adaptee.

     For object adaptersAn adapter can adapt multiple sources to the same target. In other words, the same adapter can adapt both the source class and its subclass to the target interface. Because the Object Adapter uses the relationship between object combinations, it doesn't matter if the object type is correct or not.

For Class adaptersThe adapter can redefine partial behavior of adaptee, which is equivalent to partial implementation of sub-classes that overwrite the parent class.

     For object adaptersIt is difficult to redefine the behavior of adaptee. In this case, you need to define the subclass of adaptee to implement redefinition, and then let the adapter combine the subclass. Although it is difficult to redefine adaptee behavior, it is convenient to add some new behavior, and the newly added behavior can be applied to all sources at the same time.

For Class adaptersOnly one object is introduced, and no additional reference is required to indirectly obtain adaptee.

     For object adapters, You need additional references to indirectly obtain adaptee.

We recommend that you use the Object Adapter implementation method as much as possible, and use synthesis/aggregation instead of inheritance. Of course, you can select the implementation method based on the specific analysis of specific problems. The most suitable is the best.

Advantages of the adapter Mode
  • Better reusability

The system needs to use existing classes, and such interfaces do not meet the requirements of the system. The adapter mode enables better reuse of these functions.

  • Better scalability

When implementing the adapter function, you can call your own developed functions to naturally expand the system functions.

Disadvantages of adapter Mode

Using too many adapters will make the system messy and difficult to grasp as a whole. For example, we can see that the called a interface is actually adapted to the implementation of B interface internally. If there are too many systems, this would be a disaster. Therefore, if not necessary, you can directly refactor the system without using the adapter.

 

 

 

Default Adaptation Mode

The default adapter mode provides a default implementation for an interface, so that the type can be extended from this default implementation instead of the original interface. As a special case of the adapter mode, the default adaptation mode has special applications in the Java language.

Lu zhishen's story

What do monks do? Eat fast, read Sutra, sit, hit clock, Xi Wu, etc. If you design a monk interface and provide all methods that need to be implemented, the interface should be as follows:

Public interface monk {public void chuzhai (); Public void chanting (); Public void meditation (); Public void hitting clock (); Public void Xi Wu (); public String getname ();}

Obviously, all Monk classes should implement all the methods defined by interfaces, otherwise they will not be able to use the Java editor. Similar to the following Lu zhishen class.

Public class Lu Zhi-Shen implements monk {public void Xi Wu () {boxing town Kansai; Wutai Mountains; Maha peach blossom village; burning waguan temple; pulling down willow;} Public String getname () {return "Lu zhishen ";}}

 

Lu zhishen only implements the getname () and XI Wu () methods, but does not implement any other methods. Therefore, it does not pass through the Java compiler. Lu zhishen class can only use Java compiler to implement all methods of monk interface, but Lu zhishen is no longer Lu zhishen. Learn from history and know the world. Studying how Lu zhishen shaved a Monk several hundred years ago will inspire Java programming. Good, when Ruda shaves, the monk said: "This person describes ugliness, looks stubborn, do not shave him", but the elders said: "This person is straight to the stars and heart. Although the current fierce, hit complex, but after a long time but clean. The evidence is remarkable, and you are inferior to him ."

So it turns out! It seems that the problem will be solved as long as a star is used here! If you use an object-oriented language, you can implement it as well. If you are a "Star", you can also use an abstract class.

Public abstract class tianxing implements monk {public void eat Zhai () {} public void read Sutra () {} public void SIT () {} public void hit clock () {} public void Xi Wu () {} Public String getname () {return NULL ;}}

 

Lu zhishen inherits the abstract class "tianxing"

Public class Lu Zhi-Shen extends monk {public void Xi Wu () {boxing town Kansai; Wutai Mountains; dahuan peach blossom village; burning waguan temple; pulling down willow;} Public String getname () {return "Lu zhishen ";}}

The abstract star category is an adapter class, and Lu zhishen actually achieved the purpose of shaving by means of the adapter mode. This adapter class implements all the methods required by the monk interface. However, unlike the usual adapter mode, the implementation of all the methods provided by this adapter class is "mediocre. This "mediocre" adapter mode is called the default adaptation mode.

In many cases, a specific class must implement an interface, but this class does not use all the methods specified by the interface. The common solution is to implement all methods in this specific class, implement useful methods, and implement idle and mediocre methods.

These empty methods are a waste and sometimes a mess. Unless you have read the code for these empty methods, the programmer may think that these methods are not empty. Even if he knows that some of the methods are empty, he does not necessarily know which methods are empty and which are not empty unless he has read the source code or documentation of these methods.

The default adaptation mode can handle this situation well. You can design an abstract adapter class to implement the interface. This abstract class provides an empty method for each method required by the interface. Just like Lu zhishen's "Shang Ying tianxing", this abstract class can save its specific subclass from being forced to implement null methods.

Structure of the default Adaptation Mode

The default adaptation mode is a "mediocre" adapter mode.

 

public interface AbstractService {    public void serviceOperation1();    public int serviceOperation2();    public String serviceOperation3();}

 

public class ServiceAdapter implements AbstractService{    @Override    public void serviceOperation1() {    }    @Override    public int serviceOperation2() {        return 0;    }    @Override    public String serviceOperation3() {        return null;    }}

 

As you can see, the interface abstractservice requires defining three methods: serviceoperation1 (), serviceoperation2 (), and serviceoperation3 (); abstract adapter serviceadapter provides mediocre implementation for all three methods. Therefore, any specific class that inherits from the abstract class serviceadapter can select the method implementation it requires, without worrying about other unnecessary methods.

  Intention of the adapter ModeIs to change the source interface, so that the target interface is compatible.The default adaptation has a slightly different intention.It is a mediocre implementation provided to facilitate the establishment of a non-mediocre adapter class.

At any time, if you do not want to implement all the methods of an interface, you can use the "Default Adaptation Mode" to create an abstract class and give a mediocre implementation of all methods. In this way, the subclass inherited from this abstract class does not have to implement all the methods.

 

 

 

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.