Java design Pattern Adapter pattern _java

Source: Internet
Author: User
Tags advantage

Thanks to "The Android source design pattern analysis and the actual combat" He Honghui Guan

The adapter pattern is extremely high in our development and can be judged from the adapter that are ubiquitous in the code, from the earliest ListView, the GridView, to the current Recyclerview all need to use adapter, and the optimization problems we encounter in development , the probability of greater error is also basically from adapter.

Adapters are two incompatible fire dragons fused together, different things through a transformation so that they can collaborate, for example, often encounter to the two types of no relationship between the interaction, the first solution is to modify the interface of their own classes, But if there is no source code or we do not want to modify the interface for an application, we tend to use a adapter, which is compatible with the two interfaces and satisfies the requirements without modifying the original code.

Suppose you already have a software system that you want to use with a new vendor class library, but the interface that this new vendor designs does not need to be in the old vendor's interface:

You do not want to change the existing code to solve this problem (also can not change the manufacturer's code), what should be done? You can write a class (adapter), transfer the new vendor interface to the interface you expect, and the adapter works like a middleman, converting a request made by a customer into a request that the vendor class understands.

Adapter patterns can be divided into two types:

Object adapters: full of good oo design principles, using an object combination, you can apply a method where the adapter is an interface and all of its subclasses and cannot override the adapters because there are no inheritance relationships, but it is also possible to "recreate" the methods in the adapter, the client and the adapter completely irrelevant, Only the adapter has a reference to a suitable person.

class Adapters: working with inheritance to fit the job, only the adapter is an interface, cannot take advantage of its subclass of the interface, when the class adapter is established, it is statically associated with the adapter, the adaptor as the base class, so adapters can override the methods in the adapter. Client code is visible to the code declared in the adapter by the client code that is declared in the adapter.

Definition:

The adapter pattern transforms the interface of a class into another interface that the client expects, so that two classes that cannot work together because of an interface mismatch can work together.

Usage Scenarios:

1. The system needs to use existing classes, which do not conform to the requirements of the system, that is, incompatible interfaces.

2. Want to create a reusable class that works with some classes that don't have too much association with one another, including some that might be introduced in the future.

3. A unified output interface is required, and the type of the input is unpredictable.

UML Class Diagram:

First look at the following class adapters:

The class adapter implements the interface transformation by implementing the target interface and inheriting the Adaptee class, for example, the target interface needs operation2, but the Adaptee object has only one operation3, so there is an incompatibility. This is achieved by implementing a Operation2 function by adapter to convert the Adaptee Operation3 to the operation2 required by target.

Target : The goal role, which is the desired interface. Note: Because the class adapter pattern is discussed here, the target cannot be a class.

adaptee: Now you need an adapter interface.

Adapter: adapter role, also the core of this mode, the adapter converts the source interface to the target interface. This role can not be an interface, but must be a concrete class.

Example of a class adapter pattern:

With the mainland voltage of 220v, mobile phone voltage of 5v as an example

/** * Voltage class target targets * @author Administrator * */public interface Voltage {public I
NT Getvoltage ();
 }public class Chinavoltage implements voltage{@Override public int getvoltage () {//continental voltage is 220; }<pre name= "code" class= "java" >/** * Mobile phone class, adaptee by the adapter class * @author Administrator * * * * public class Phonevoltag
 e {/** * mobile phone voltage of 5v * @return * * * public int getphonevoltage () {return 5; } <pre name= "code" class= "java" >/** * Charger Adapter Adapter Class * @author Administrator * * */public class Charger ex
 Tends Phonevoltage implements voltage {@Override public int getvoltage () {return getphonevoltage ();
 } public class Client {public static void main (string[] args) {Chinavoltage vol. = new Chinavoltage ();
 System.out.println ("Continental voltage is:" + vol.getvoltage ());
 The voltage chargerr character = new Chargerr () when the charger is connected to the mobile phone;
 System.out.println ("Voltage converted via charger:" + character.getvoltage ()); }
}

Run Result:
The voltage of the mainland is: 220
Voltage after conversion via charger: 5

Look at the object adapter class diagram again:

The following modifies the Chargerr class with the object adapter

<pre name= "code" class= "java" >/**
 * Charger Adapter Adapter Class
 * @author Administrator
 *
 /
Public Class Chargerr implements voltage{
 private phonevoltage Phonev;
 
 Public Chargerr (Phonevoltage Phonev) {
 This.phonev = Phonev;
 }
 
 @Override public
 int Getvoltage () {return
 phonev.getphonevoltage ();
 }
}

The object adapter implementation will be passed directly to the adapter object, the effect of interface compatibility using a combination is more flexible than a class adapter, and another advantage is that the methods in the adapter are not exposed, and the class adapter inherits the adaptive object, so The function of the Adaptive object class is also included in the adapter class, which makes the adapter class appear some strange interfaces, the user cost is high. Therefore, the object adapter pattern is more flexible and practical.

public class Client {public
 static void Main (string[] args) {
//Chinavoltage vol. = new Chinavoltage ();
System.out.println ("Continental voltage is:" + vol.getvoltage ());
Voltage
//Chargerr character = new Chargerr () for mobile phone access to charger;
System.out.println ("Voltage converted via charger:" + character.getvoltage ());
 The adapter
 phonevoltage Phonev = new Phonevoltage ();
 Chargerr Chargerr = new Chargerr (Phonev);
 System.out.println ("Voltage converted via charger:" + chargerr.getvoltage ());
 
 }
 Operation Result:
 //the voltage converted by the charger: 5
}

Summarize:
the classic implementation of the adapter model is to combine incompatible interfaces so that they can work well together. However, in the actual development, the adapter model also has some flexible implementation. For example, the isolation changes in ListView make the entire UI architecture more flexible and able to embrace change. Adapter mode is widely used in the development of LU.

Advantages:

Better reusability: The system needs to use existing classes, and the interfaces of this class do not conform to the needs of the system. Then the adapter mode allows these functions to be better reused.

Better scalability: When implementing adapter functionality, you can invoke your own developed functionality to naturally extend the functionality of the system.

Disadvantages:

Excessive use of adapters, will make the system very messy, not easy to grasp the speed. For example, clearly see the call of Chang a interface, in fact, the internal is adapted to the implementation of the B interface, a system if too much of this situation, is tantamount to a disaster. Therefore, if it is not necessary, you can not use the adapter, but directly to the system refactoring.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.