Adapter mode The English text is: Convert the interface of a class into anther interface clients expect. Adapter lets classes work together that Couldni ' t otherwise because of incompatible interface. It means changing 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.
The adapter mode has the following three roles:
Target role: The interface the customer expects
Source Role (Adaptee): The original role that needs to be converted to the target role
Adaptive Role (Adapter): Converts a source role to a target role through inheritance or class affinity
Adapter class Diagram:
Each class implements the code:
SOURCE role:
Package com.zz.adapter;/** * Source role * Copyright April 22, 2015 * created by TXXS * All right reserved */public class Adaptee {//original There is business processing public void Spcificrequest () {}}
Target role:
Package com.zz.adapter;/** * Target Role interface * Copyright April 22, 2015 * created by TXXS * All right reserved */public interface Targe t {public void request ();}
Adapter role:
Package com.zz.adapter;/** * Adapter Role * Copyright April 22, 2015 * created by TXXS * All right reserved * According to the uniqueness of inheritance can only be adapted to Adaptee */p Ublic class Adapter extends Adaptee implements Target {@Overridepublic void request () {super.spcificrequest ();}}
Client:
Package com.zz.adapter;/** * Test class * Copyright April 22, 2015 * created by TXXS * All right reserved */public class Client {Publ IC static void Main (String args[]) {//adapter apply target target = new Adapter (); Target.request ();}}
Advantages of the adapter mode:
1. You can combine any two classes that are not associated with each other.
2, increase the transparency of the class, through the adapter, the client can call the same interface, and therefore transparent to the client.
3, improve the flexibility of the code.
4, reuse of existing classes, improve the reusability.
Scenarios that can be used:
1, the system needs to use the existing classes, and these classes of interfaces do not conform to the interface of the system.
2. Want to create a reusable class to work with some classes that are not much related to each other, including some that might be introduced in the future.
3, two classes do things the same or similar, but with different interfaces.
4, the old system development class has implemented some functions, but the client can only be accessed in the form of a different interface, but we do not want to manually change the original class.
5, the use of third-party components, component interface definitions and their own definition of the different, do not want to modify their own interfaces, but to use the functionality of the third-party component interface.
Refer to http://blog.csdn.net/elegant_shadow/article/details/5006175 for adapter mode
Design mode-Adapter mode