Android design mode Adapter (Adapter) mode _android

Source: Internet
Author: User
Tags wrapper

This example for you to share the Android adapter mode source code for your reference, the specific content as follows

1. Model Introduction

Definition of the 1.1 pattern:

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.

1.2 Usage Scenarios for mode:

Use the Power interface as an example, the laptop power supply is generally accept 5V voltage, but our life in the wire voltage is generally 220V output. This time there is a mismatch of the situation, in software development, we call it incompatible interface, at this time need adapters to do an interface conversion. In software development, there is a sentence that reflects this: any problem can be added to a middle layer to solve. This layer can be understood as the adapter layer here, through which an interface conversion is achieved for compatibility purposes.

2. The simple realization of the pattern

2.1 Introduction to Simple implementations:

In the example above, the 5V voltage is the target interface, and the 220v voltage is the Adaptee class, and switching the voltage from 220V to 5V is adapter.

Class 2.2 Adapter Mode:

 /**
 * Target role
/public interface Fivevolt {public
  int getVolt5 ();
}

/**
 * adaptee role, the object that needs to be converted
/public class Volt220 {public
  int getVolt220 ()
  }
}

Adapter role Public
class Classadapter extends Volt220 implements Fivevolt {

  @Override public
  int GETVOLT5 () {return
    5;
  }

}

The target role gives the desired interface, and the Adaptee class is the object that needs to be converted. Adapter is the interface that converts Volt220 to target. The target is to obtain the 5V output voltage, and adaptee is the normal output voltage is 220V, at this time we need the power adapter class will 220V voltage to the 5V voltage, solve the problem of incompatible interface.

public class Test {public
  static void Main (string[] args) {
    Classadapter adapter = new Classadapter ();
    SYSTEM.OUT.PRINTLN ("Output voltage:" + ADAPTER.GETVOLT5 ());
  }

2.3.Android mode implementation in the source code

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

As you can see from Figure 2, the Adaptee Class (Volt220) does not have the GETVOLT5 () method, and the client expects this method. To enable clients to use the Adaptee class, you need to provide a wrapper class adapter. This wrapper class wraps a Adaptee instance so that the wrapper class can connect the Adaptee API with the target class API. Adapter and Adaptee are delegated, which determines that the adapter pattern is an object.

/**
 * Target role
/public interface Fivevolt {public
  int getVolt5 ();
}

/**
 * adaptee role, the object that needs to be converted
/public class Volt220 {public
  int getVolt220 ()
  }
}

Object Adapter mode Public
class Objectadapter implements Fivevolt {

  Volt220 mVolt220;

  Public Objectadapter (Volt220 adaptee) {
    mVolt220 = adaptee;
  }

  public int getVolt220 () {return
    mvolt220.getvolt220 ();
  }

  @Override public
  int GetVolt5 () {return
    5;
  }

}

2.4. The tradeoff between class adapters and object adapters

* Class adapters are statically defined by using object inheritance, and object adapters are dynamically grouped by the way they are grouped.

* 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 deal with Adaptee subclasses. For an object adapter, an adapter can fit a variety of different sources to the same target. In other words, the same adapter can fit both the source class and its subclasses to the target interface. Because the object adapter uses the relationship of the object mix, it doesn't matter if the object type is correct and not subclasses.

* For class adapters, the adapter can redefine part of the behavior of the adaptee, which is equivalent to a subset of the implementation methods that the subclass overrides the parent class. 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 let the adapter combine the subclasses. Although it is difficult to redefine the behavior of adaptee, 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 adapters, only one object is introduced, and no additional references are required to get adaptee indirectly. For object adapters, additional references are required to get adaptee indirectly.

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

Adapter mode in the 3.Android listview

In the development process, ListView's adapter is one of our most common types. The general usage is roughly as follows:

  Adapter public class Myadapter extends baseadapter{private layoutinflater minflater;

    List<string> Mdatas;
      Public Myadapter (context context, list<string> datas) {this.minflater = Layoutinflater.from (context);
    Mdatas = datas;
    @Override public int GetCount () {return mdatas.size ();
    @Override public String getitem (int pos) {return mdatas.get (POS);
    @Override public long Getitemid (int pos) {return pos; }//parsing, setting, caching Convertview and related content @Override public View getview (int position, View Convertview, ViewGroup Parent
      ) {Viewholder holder = null; 
        Item View's Duplicate if (Convertview = = null) {holder = new Viewholder ();
        Convertview = minflater.inflate (R.layout.my_listview_item, NULL);
        Gets title Holder.title = (TextView) Convertview.findviewbyid (r.id.title);
      Convertview.settag (holder); else {holder = (viewhoLder) Convertview.gettag ();
      } holder.title.setText (Mdatas.get (position));
    return convertview;

 }

  }

This seems to be quite troublesome, see here we can not help but ask, why ListView use adapter mode?
We know that as the most important view,listview need to be able to display a wide variety of views, each person needs to display different effects, the display of data types, the number of the ever-changing. So how to isolate this change is particularly important.

Android's approach is to add a adapter layer to deal with the changes, the ListView needed to abstract the interface to the adapter object, so long as the user to achieve the adapter interface, ListView can be set according to user's display effect, number, Data to display a specific item View.
By using the proxy dataset to tell the number of ListView data (GetCount function) and the type of each data (GetItem function), the most important thing is to solve the item view output. Item view is ever-changing, but after all it is a view type, adapter unified the item view output to view (GetView function), so that it is good to deal with the item view variability.

So how does ListView work through adapter mode (more than adapter mode)? Let's take a look at it together.
ListView inherits from Abslistview,adapter definition in Abslistview, let's take a look at this class.

Public abstract class Abslistview extends adapterview<listadapter> implements Textwatcher, Viewtreeobserver.ong Loballayoutlistener, Filter.filterlistener, Viewtreeobserver.ontouchmodechangelistener, RemoteViewsAdapter.Remote

  adapterconnectioncallback {ListAdapter madapter;
    function called when associating to window @Override protected void Onattachedtowindow () {Super.onattachedtowindow ();
    The code omits//registers an observer with the adapter, which is described in the next article.
      if (madapter!= null && mdatasetobserver = null) {Mdatasetobserver = new adapterdatasetobserver ();

      Madapter.registerdatasetobserver (Mdatasetobserver); Data may have changed while we were detached.
      Refresh.
      Mdatachanged = true;
    Molditemcount = Mitemcount//Gets the number of the item, which is called the Madapter GetCount method mitemcount = Madapter.getcount ();
  } misattached = true; /** * Subclasses need to overwrite the Layoutchildren () function to lay out the child view, which is Item View/@Override protected void OnLayout (Boolean Chang Ed, int L, int t, int r, int b) {super.onlayout (changed, L, T, R, b);
    Minlayout = true;
      if (changed) {int childcount = Getchildcount ();
      for (int i = 0; i < ChildCount i++) {getchildat (i). Forcelayout ();
    } mrecycler.markchildrendirty (); } if (Mfastscroller!= null && mitemcount!= molditemcount) {mfastscroller.onitemcountchanged (Molditem
    Count, Mitemcount);
    }//Layout child View Layoutchildren ();

    Minlayout = false;
  Moverscrollmax = (b-t)/overscroll_limit_divisor;
    //Get an Item View view Obtainview (int position, boolean[] isscrap) {isscrap[0] = false;
    View Scrapview;

    Obtained from the cached item view, the ListView multiplexing mechanism is here Scrapview = Mrecycler.getscrapview (position);
    View child;
      if (Scrapview!= null) {//code omits child = Madapter.getview (position, Scrapview, this);
      Code omitted} else {child = Madapter.getview (position, NULL, this);
  Code omitted} return child;
} }


 

Abslistview defines the framework for the set view, such as the application of the adapter pattern, the logic of the reuse item view, and the logic of the layout item view. Subclasses only need to overwrite specific methods to implement the functionality of the collection view, such as ListView.

The related methods in ListView.

  @Override protected void Layoutchildren () {//code omits try {super.layoutchildren ();
      Invalidate (); Code omitted//Layout item View switch (mlayoutmode) {case layout_set_selection:if (Newsel!= nu by layout mode)
        LL) {sel = Fillfromselection (Newsel.gettop (), Childrentop, Childrenbottom);
        else {sel = Fillfrommiddle (Childrentop, Childrenbottom);
      } break;
        Case Layout_sync:sel = fillspecific (msyncposition, mspecifictop);
      Break
        Case Layout_force_bottom:sel = FillUp (mItemCount-1, Childrenbottom);
        Adjustviewsupordown ();
      Break
        Case layout_force_top:mfirstposition = 0;
        sel = Fillfromtop (childrentop);
        Adjustviewsupordown ();
      Break
        Case Layout_specific:sel = fillspecific (Reconcileselectedposition (), mspecifictop);
      Break Case Layout_move_selection:sel = moveselection (Oldsel, NewseL, Delta, Childrentop, Childrenbottom);
      Break
      Default://code omits break;

    Fill item View from top to bottom [just one of the padding] private view filldown (int pos, int nexttop) {view Selectedview = null;
    int end = (mbottom-mtop);
    if (mgroupflags & clip_to_padding_mask) = = Clip_to_padding_mask) {end-= Mlistpadding.bottom;
      } while (Nexttop < end && Pos < Mitemcount) {/are this the selected item?
      Boolean selected = pos = = mselectedposition;

      View child = Makeandaddview (pos, Nexttop, True, Mlistpadding.left, selected);
      Nexttop = Child.getbottom () + mdividerheight;
      if (selected) {Selectedview = child;
    } pos++;
  return selectedview; //Add Item View private view Makeandaddview (int position, int y, boolean flow, int childrenleft, Boolean Selec

    Ted) {View child; Code omitted//Make a new view for this position, or convert a unused view IF Possible child = Obtainview (position, misscrap); 

    This is needs to being positioned and measured setupchild (child, position, y, Flow, Childrenleft, selected, misscrap[0]);
  return to child;


 }

ListView Abslistview The Layoutchilden function in the function, in which the item View is laid out according to the layout pattern. Item view number, style all through adapter corresponding method to obtain, get the number, item view, the Item view layout to listview corresponding coordinates, plus the item view of the reuse mechanism, The whole ListView is basically working.

Of course, the adapter is not a classic adapter pattern, but it is an excellent example of object adapter mode, and it also embodies some of the basic principles of object-oriented. The target role and the adapter role are fused together, and the method in adapter is the goal method, and the Adaptee role is the ListView dataset and the item View,adapter proxy dataset, obtaining the number and elements of the dataset.

By adding a layer of adapter to abstract the operation of item view, the ListView collection View obtains item number, data element, item view and so on by adapter object, thus achieves the effect of various data and various item views. Because item view and data type are ever-changing, Android architects give these changes to the user for processing, abstracted by GetCount, GetItem, GetView, and so on, which is the construction of the item view to the user to process, Flexible use of adapter mode, to achieve unlimited adaptation, embracing the change.

4. The topics

Advantages and Disadvantages

Advantages

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

Better scalability
When implementing the adapter functionality, you can invoke the functionality that you develop to naturally extend the functionality of the system.

Disadvantages

Excessive use of adapters, will make the system very messy, not easy to grasp the overall. For example, clearly see the call is a interface, in fact, the internal is adapted to the implementation of the B interface, a system if too many occurrences 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.

Related Article

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.