Java design mode-adapter (adapter mode)

Source: Internet
Author: User

The adapter mode transforms the interface of one class into another interface that the client expects, so that two classes that would otherwise not work together because of an interface mismatch can work together.

Structure of the adapter pattern

The adapter mode has two different forms of adapter mode for the class and the adapter mode of the object .

Class Adapter Mode

The adapter mode of the class transforms the API of the class that is adapted into the API of the target class.

As you can see, the Adaptee class does not have a sampleOperation2 () method, and the client expects this method. To enable clients to use the Adaptee class, provide an intermediate link, the class adapter, to connect Adaptee APIs with the target class API. Adapter and adaptee are inheritance relationships, which determines that the adapter pattern is class:

The roles involved in the pattern are:

target role: This is the interface you expect to get. Note: Because the class adapter pattern is discussed here, the target cannot be a class.

Source (adapee) role: A suitable interface is now required.

Adapter (adaper) Role: The adapter class is at the heart of this pattern. The adapter converts the source interface into the target interface. Obviously, this role cannot be an interface, but must be a concrete class.

Source
Interface Target {    /**     * This is the source class Adaptee there are methods     void/**void SampleOperation2 ( ); }

The above gives the source code of the target role, which is implemented in the form of a Java interface. As you can see, this interface declares two methods: SampleOperation1 () and SampleOperation2 (). The source role, Adaptee, is a concrete class that has a SampleOperation1 () method, but no SampleOperation2 () method.

Class Adaptee {        void sampleOperation1 () {}}  

The adapter role adapter extends the Adaptee and also implements the target interface. Because Adaptee does not provide the SampleOperation2 () method, and the target interface requires this method, the adapter role adapter implements this method.

Implements Target {    /***/void// write-related Code }}      
Object Adapter Mode

As with the class's adapter pattern, the object's adapter pattern transforms the API of the class being adapted into the API of the target class, unlike the class's adapter pattern, where the object's adapter pattern is not connected to the Adaptee class using an inheritance relationship, but instead uses a delegation relationship to connect to the Adaptee class.

As you can see, the Adaptee class does not have a sampleOperation2 () method, and the client expects this method. To enable clients to use the Adaptee class, you need to provide a wrapper (Wrapper) class adapter. This wrapper class wraps a Adaptee instance so that the wrapper class can link the API of Adaptee with the API of the target class. Adapter and Adaptee are delegated relationships, which determines that the adapter pattern is an object.

Source
Interface Target {    /**     * This is the source class Adaptee there are methods     void/**void SampleOperation2 ( ); }
Class Adaptee {    void sampleOperation1 () {}}  
PublicClassAdapter {PrivateAdaptee adaptee;PublicAdapter (Adaptee adaptee) {this.adaptee = Adaptee;} /** * source class Adaptee There are methods SampleOperation1 * So the adapter class can be delegated directly */public voidthis.adaptee.sampleoperation1 () ; } /** * Source Class Adaptee No method SampleOperation2 * Therefore the adapter class needs to supplement this method Span style= "color: #008000;" >*/public void// Write related code             /span>      
Trade-offs between class adapters and object adapters

The way that class adapters use object inheritance is statically defined, and how object adapters use object composition is a dynamic combination.

for class adapters , because the adapter inherits Adaptee directly, the adapter cannot work with adaptee subclasses, because inheritance is a static relationship, and when the adapter inherits Adaptee, it is impossible to process the subclass of Adaptee.

     for object adapters , an adapter can adapt many different sources to the same target. In other words, the same adapter can adapt the source class and its subclasses to the target interface. Because the object adapter is a combination of objects, it doesn't matter if the object type is correct.

for class adapters , the adapter can redefine part of the behavior of Adaptee, which is equivalent to a partial implementation of the parent class that the subclass overrides.

     for object adapters , it is difficult to redefine the behavior of Adaptee, in which case you need to define a subclass of Adaptee to implement the redefinition and then have the adapter group the subclasses. Although it is difficult to redefine the behavior of adaptee, it is convenient to add some new behaviors, and the newly added behavior can be applied to all sources at the same time.

for class adapters , only one object is introduced, and no additional references are required to indirectly get adaptee.

     for object Adapters , additional references are required to get adaptee indirectly.

It is recommended to use the implementation of object adapters as much as possible, using compositing/aggregation and less inheritance. Of course, specific problems specific analysis, according to the need to choose the implementation, the most suitable is the best.

Benefits of Adapter Mode
    • Better reusability

The system needs to use the existing classes, and the interfaces of this class do not meet the needs of the system. The adapter mode allows for better reuse of these features.

    • Better extensibility

When implementing the adapter functionality, you can invoke the features you have developed to naturally extend the functionality of the system.

Disadvantages of Adapter Mode

Excessive use of the adapter, will make the system very messy, not easy to grasp the overall. For example, clearly see the call is a interface, in fact, the interior is adapted to the implementation of the B interface, a system if too many occurrences of this situation, is tantamount to a disaster. So if it's not necessary, you can refactor the system without using the adapter.

Default adaptation mode

The default adaptation (default Adapter) mode provides a default implementation for an interface, which can be extended from this default implementation without having to scale from the original interface. As a special case of the adapter pattern, the default is that the adaptation mode has a special application in the Java language.

The story of Lu Zhishen

What does a monk want to do? Chizhai, chanting, meditation, bell, martial arts and so on. If you design a monk interface and give all of the methods that all monks need to implement, then this interface should look like this:

interface Monk {void void void void void public     String getName ();   

Obviously, all monk classes should implement all the methods defined by the interface, or they will not pass through the Java language editor at all. Not like the LU Zhishen class below.

Implements Monk {    voidpublicreturn ' Lu Zhishen ';}}    

Since Lu Zhishen only implements the GetName () and the martial arts () method, no other method is implemented. As a result, it simply doesn't pass the Java language compiler. The LU Zhishen class can only implement all the methods of the monk interface through the Java language compiler, but this LU Zhishen is no longer Lu Zhi deep. With history as a mirror, you can know the world. The study of how Lu Zhishen was tonsure hundreds of years ago is a great inspiration for Java programming. Good, the original Tangolunda tonsure, the monks said: "This person describes the ugly, appearance gangsters, not tonsure him", but the elder said: "This person should be star, heart outspoken." Although nowadays gangsters, hit complex, long after but have to clean. The fruit of your testimony is extraordinary, and thou shalt not him. ”

I see! It seems that as long as there should be a star, the problem is solved! In the case of object-oriented language, the "should" person, the realization also; "Star", abstract class also.

PublicAbstractClass Sky Starimplements Monk {public Span style= "color: #0000ff;" >void Chizhai () {} public  chanting () {} public void  meditation () {} public void< Span style= "color: #000000;" > Bell () {} public void martial arts ( {} public String GetName () { return null   

Lu Zhishen class inherits abstract class "Tian Xing"

Extends monk {    voidpublicreturn ' Lu Zhishen ';}}    

This abstract star class is an adapter class, and Lu Zhishen actually uses the adapter mode to achieve the tonsure. This adapter class implements all the methods required by the monk interface. However, unlike the usual adapter pattern, the implementation of all the methods given by this adapter class is "mediocre". This "mediocre" adapter pattern is called the default adaptation mode.

In many cases, it is necessary to have a specific class implement an interface, but this class does not use all the methods specified by the interface. The usual way to do this is for this particular class to implement all of the methods, those that are useful to be implemented, and those that are not used are empty and mediocre implementations.

  These empty methods are a waste, and sometimes a kind of confusion. Unless you have seen the code for these empty methods, programmers may think that these methods are not empty. Even if he knows that some of these methods are empty, they don't necessarily know which methods are empty and which are not, unless you've seen the source code or the documentation for those methods.

The default adaptation mode is a good way to handle this situation. An abstract adapter class can be designed to implement an interface that provides an empty method for each method required by the interface. Just like the LU Zhishen star, this abstract class can keep its specific subclasses from being forced to implement empty methods.

structure of the default adaptation mode

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

  

Interface Abstractservice {    voidintpublic String ServiceOperation3 ();}    
Implements abstractservice{    @Override    voidintreturn 0publicnull;}}  

As you can see, the interface Abstractservice requires the definition of three methods, namely ServiceOperation1 (),serviceOperation2 (),ServiceOperation3 () , and the abstract adapter class Serviceadapter provides a mediocre implementation for all three of these methods. Therefore, any concrete class that inherits from the abstract class Serviceadapter can choose the method implementation that it needs, regardless of the other unwanted methods.

  the adapter mode is intended to change the interface of the source so that it is compatible with the target interface. The default adaptation is slightly different , and it is a mediocre implementation provided to facilitate the creation of a non-mediocre adapter class.

At any time, if you are not ready to implement all of the methods of an interface, you can use the default adaptation mode to create an abstract class that gives a concrete implementation of the mediocrity of all methods. Thus, subclasses that inherit from this abstract class do not have to implement all the methods.

Transfer from http://www.cnblogs.com/java-my-life/archive/2012/04/13/2442795.html

Java design mode-adapter (adapter mode)

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.