Design mode 08_ Adapter mode

Source: Internet
Author: User

This article is in the study summary, welcome reprint but please specify Source:

1. Definition

The adapter pattern transforms the interface of a class into another interface that the customer expects. Adapters allow classes that are inherently incompatible to work together. (excerpt from head first Chinese 243 page)

2. Description

There are typically two types of adapter modes: Object adapters and Class adapters. The adapter pattern of the class is implemented by inheritance, and object adapters are implemented by object composition.

The class adapter uses inheritance (statically) so that the adapter cannot work with the Adaptee subclass. When the number of target classes becomes more and more complex with the business requirements, the code structure becomes complicated and difficult to maintain; The object adapter uses the combination of objects (dynamic composition), and an adapter can adapt many different sources to the same target. That is, the same adapter can match the source class and the subclass of the source class to the target interface. Therefore, in the actual situation, it is recommended to use the object adapter as much as possible, that is, multi-use combination, less inheritance. But for the specific problem, still need to choose the right way to achieve.

When do I use the adapter mode? One scenario is that you want to use a class that already exists and that its interface does not meet your needs. You are going to create a reusable class that can work with other unrelated classes or unforeseeable classes (that is, classes that are incompatible between interfaces), and you might consider using adapter mode. Another scenario is that you want to use some already existing classes, but it is not possible to subclass each class to match their interfaces, then consider using the (object) adapter pattern (The object adapter can be adapted to its parent class interface).

3. Role

Target interface: The interface that the customer expects, the specific class, the abstract class, the interface.

Classes to be adapted (Adaptee): Classes that need to be fitted.

Adapter (Adapter): Wraps an object that needs to be adapted, converting the original interface into the target interface.

4. Class Diagram

5. Example

Examples of class adapters are as follows:

package;/** * 已存在的、具有特殊功能、但不符合我们既有的标准接口的类 */publicclass Adaptee {    publicvoidspecialMethod() {        System.err.println("这是一个经过适配的特殊的方法");    }}
package; /** * Define interface expected by client */ public  interface  Itarget  {  public  void   Method  ();}  
package; /** * Adapter, call method () on the surface, actually call Specialmethod () */ public  class  adapter  extends  adaptee      Implements  itarget  {  @Override  public  void  method     () {super . Specialmethod (); }}
package;publicclass Test {    publicstaticvoidmain(String[] args) {        new Adapter();        adapter.method();    }}

An example of an object adapter is shown below:

package;/** * 男人相关接口 */publicinterface IMen {    publicvoidrun();    publicvoidsleep();    publicvoidgroupBaby();};/** * Specific class * / Public  class  men implements imen {    @Override     Public void Run() {System.err.println ("Men run Fast"); }@Override     Public void Sleep() {System.err.println ("Men Want Sleep"); }@Override     Public void Groupbaby() {System.err.println ("Men can group Baby"); }}
package;/** * 女人相关接口 * */publicinterface IWomen {    publicvoidwomenrun();    publicvoidwomensleep();    publicvoidwomencreatBaby();};/** * Specific class * @author LIQQC * */ Public  class women implements iwomen {    @Override     Public void Womenrun() {System.err.println ("Women run Slow"); }@Override     Public void Womensleep() {System.err.println ("Women need to sleep"); }@Override     Public void Womencreatbaby() {System.err.println ("Women can create baby"); }};/** * to fit a man * * * Public  class Adapter implements iwomen {    PrivateImen men; Public Adapter(Imen men) {Super(); This. Men = Men; }@Override     Public void Womenrun() { (); }@Override     Public void Womensleep() {men.sleep (); }@Override     Public void Womencreatbaby() {Men.groupbaby (); }}
package; Public  class  Test {public  static  void  main  (string[] args) {Men's men = new  men ();        //Create a man  Women women = new  women ();        //Create a woman  Iwomen awomen = new  Adapter (men);        //to wrap the man into a woman adapter to make him look like a woman  awomen.womenrun ();        Awomen.womensleep ();        Awomen.womencreatbaby ();        System.err.println ( "women ..." );        Women.womenrun ();        Women.womensleep ();    Women.womencreatbaby (); }}
Console:sleepsleepwomen can create baby
6. Summary

There are two main design modes used in Java IO: Decorator mode and adapter mode. Decorator mode has been elaborated in a previous article. Here is a brief description of the adaptation mode in Java IO. View IO source code can be found:

 Public  class inputstreamreader extends Reader {    Private FinalStreamdecoder SD;/** * Creates an inputstreamreader that uses the default charset. * * @param  in an inputstream * *     Public InputStreamReader(InputStream in) {Super(in);Try{SD = Streamdecoder.forinputstreamreader (in, This, (String)NULL);//# # Check Lock Object}Catch(Unsupportedencodingexception e) {//The default encoding should always be available            Throw NewError (e); }    }

InputStreamReader's construction method is InputStream, which shows that InputStream is converted to reader, and Streamdecoder's design implementation actually uses the adapter pattern. So we often say that InputStreamReader and OutputStreamWriter do the conversion between Inputstream/outputstream and the reader/writer of the throttle class, That is, InputStreamReader and OutputStreamWriter are the bridge of byte flow to character stream.

Benefits of Adapter Mode: Good reusability. The system needs to use the existing classes, which do not meet the current needs of the system, you can use the adapter mode to make these features better reuse. Scalability is good. When implementing the adapter functionality, you can add functionality to your requirements and naturally extend the functionality of your system.

The disadvantage of adapter mode: Excessive use of the adapter in the project, will make the system code messy, bad overall grasp system. For example, on the surface of a business to see the call is interface a, but in fact, its internal is adapted to the implementation of interface B, if too many occurrences of this situation, then the system will face a disaster. In general, if it is not necessary, it is best not to use the adapter, but rather to refactor the system accordingly.

This article simply introduces the adapter mode, it is not discussed in depth, slightly rough. I hope this article will be of some help to you.

Design mode 08_ 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: 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.