-
- An introduction to Adapter mode
- What is adapter mode
- What scenarios the adapter applies To
- Two adapter mode applications in the Android framework
- Listviewbaseadapter Custom View
- Popular UML diagram
- Critical Code Analysis
- Activitybindermediaplayer
- Popular UML diagram
- Critical Code Analysis
- Three-adapter mode mates with other modes
- Adapter Watcher Template Policy combination Baseadapterlistview custom View
- Overall UML diagram
- Pattern Analysis different Perspective decision
- Adapter Watcher Template Service Activity custom Services
- Overall UML diagram
- Pattern Analysis different Perspective decision
- Iv. Summary
First, the adapter mode introduction
Adapters are often used in everyday life, especially in electronic products. Like mobile phones, computers, and household appliances, adapters are used to convert the voltage to provide the right voltage. The adapter is to convert the original non-compliant voltage, circuit signal into the appropriate voltage and signal. Simply put, it is an interface converter.
What is adapter mode? Defined:
The adapter mode 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 (interface name, return parameter, input parameter, and so on) can work together.
Classification:
In software programming mode, the adapter pattern is divided into two types: Class adapter, object adapter.
Class Adapter
Object Adapter
concept : The same purpose as the class adapter: To convert the Adaptee interface into the interface required by the target. But the difference is that the object adapter is linked to the Adaptee class by using a proxy relationship, and will be adaptee as a member of adapter, and adapter as a proxy to implement Adaptee functionality.
UML Diagram
What scenario does the adapter apply to?
1. The system needs to use the existing classes, and such interfaces do not meet the needs of the system, that is, the interface is incompatible (the most common adapter);
2. Want to create a reusable class that will work on some classes that are not related to each other, including some that might be introduced in the Future (Binder Interface link activity and service,activity and service can run independently, With the binder interface, service-side services are adapted to the Transact () method identified by the activity side.
3. Need a unified output interface, and the input terminal type is unpredictable (Baseadapter is the ListView, GridView and other controls with the changeable custom view in conjunction with the adapter, the input type is a custom variable type, And the output end is always the view type)
second, the application of adapter mode in Android frame
In general, the object adapter is now preferred because the object adapter is able to hide the method of the object being adapted, and if the class adapter is used, the adapter inherits the method of the object being adapted because of the inheritance, which exposes the object to be fitted. Therefore, Android is also used in the object adapter, through the proxy method to achieve the adaptation.
listview+baseadapter+ Custom View
The combination of ListView and Baseadapter is the third case of adapter usage scenarios. That is, a unified output interface is required, and the type of the input is unpredictable.
Custom view has a variety of different view interface, so through the adapter to provide a unified output interface, can make the ListView to "unchanged should be the effect of the change."
The following UML diagram reflects the connection between activity, ListView, Baseadapter, and custom view in a general application. The Observer model here is just my own to simplify and make baseadapter directly implement observable (Notifier interface), ListView Implementation Observer interface. In fact, there is a deeper inheritance relationship between the Baseadapter and the ListView, and the Observer model is the object observer model (that is, the observer and the notifier are implemented as class members, through proxies), rather than the observer model based on the interface implementation.
Popular UML diagram:
Key Code Analysis:
In Baseadapter, the most important method is GetView (). It is a bridge linking the ListView container and the Itemview, GetView (), is a unified interface, it is fixed to return the parameters of the view type, so no matter what kind of custom view, because they are all the child classes of view, So the ListView is able to identify. This is the adaptation method in Baseadapter, the output is constant, and the input can be variable.
The //getview () method fits the custom view, assembles each sub-view, and//Then load it into a unified view and return it to the ListView. @Override PublicViewGetView(intPosition, View Convertview, ViewGroup parent) {Viewholder Holder =NULL;if(Convertview = =NULL) {holder =NewViewholder (); Convertview = View.inflate (Getbasecontext (), r.layout.activity_audiocable,NULL); Holder.mimagecover = Convertview.findviewbyid (r.id.img_cover); Holder.mtexttitle = Convertview.findviewbyid (R.id.txt_title); Convertview.settag (holder); } holder = (Viewholder) convertview.gettag (); Holder.mTextTitle.setText (String) getItem (position). GetTitle ()); Holder.mImageCover.setImageResource (String) getItem (position). Getcoverres ());returnConvertview; } class viewholder{TextView mtexttitle; ImageView Mimagecover; }
Activity+binder+mediaplayer
In Activity+binder+mediaplayer, Binder acts as an adapter. This is the second scenario used by the adapter: you want to create a reusable class that will work with some classes that are not related to each other, including some that might be introduced in the future.
In the process of starting a service, Binder is an adapter that provides the Transact () method to the framework call, Ontransact () to the application class, and the Ontransact () method that follows is the appropriate method, Docking (multimedia control, task download) with different backend services through the Ontransact method.
Popular UML diagram:
Key Code Analysis:
Let's take a look at the adaptation Method Ontransact (), by the way, if the Ontransact () method is a hook method from the frame point of view. The task of the Ontransact () method is to interface with multimedia and background tasks. In the Ontransact () method, a multimedia control method (Task control method) is invoked to provide service to the front end.
Note: Activity only knows that the Transact () method is called through binder, and the rest is adapted through Ontransact ().
Public class mp3player_adapter extends Binder{ PrivateMediaPlayer MPlayer =NULL;PrivateContext CTX; Public Mp3player_adapter(Context CX) {ctx= cx;}//Through the Ontransact () method to complete the call play () and stop (), to play the MP3 and//Stop control. @Override Public Boolean ontransact(intCode, Parcel data, Parcel reply,intFlagsthrowsandroid.os.RemoteException {reply.writestring (data.readstring () +"MP3");if(Code = =1) This. Play ();Else if(Code = =2) This. Stop ();return true; }//play (), Stop () are methods that cannot be recognized by the client and need to be adapted by Ontransact () Public void Play(){if(MPlayer! =NULL)return; MPlayer = Mediaplayer.create (CTX, R.RAW.TEST_CBR);Try{Mplayer.start (); }Catch(Exception e) {LOG.E ("Startplay","Error:"+ E.getmessage (), E); } } Public void Stop(){if(MPlayer! =NULL) {mplayer.stop (); MPlayer =NULL; } }}
Public class ac01 extends Activity implements Onclicklistener { Private Final intWC = LinearLayout.LayoutParams.WRAP_CONTENT;Private Final intFP = LinearLayout.LayoutParams.FILL_PARENT;PrivateButton btn, btn2, btn3; PublicTextView TV;PrivateIBinder IB =NULL; Public void onCreate(Bundle icicle) {//...... InitializeStartService (in);//Start service //Binding ServicesBindservice (in, Mconnection, context.bind_auto_create); }//Service connection to notify the Activity Service connection and return to the IBinder interface PrivateServiceconnection mconnection =NewServiceconnection () { Public void onserviceconnected(ComponentName className, IBinder IBinder) {IB = IBinder; } Public void onservicedisconnected(ComponentName className) {} }; Public void OnClick(View v) {Switch(V.getid ()) { Case 101: Parcel pc = Parcel.obtain (); Parcel pc_reply = Parcel.obtain (); Pc.writestring ("playing");Try{//Call adapter method operation MP3 PlayIb.transact (1, PC, Pc_reply,0); Tv.settext (Pc_reply.readstring ()); }Catch(Exception e) {E.printstacktrace (); } Break; Case 102: PC = Parcel.obtain (); pc_reply = Parcel.obtain (); Pc.writestring ("Stop");Try{//Call adapter method operation MP3 StopIb.transact (2, PC, Pc_reply,0); Tv.settext (Pc_reply.readstring ()); }Catch(Exception e) {E.printstacktrace (); } Break; Case 103: Finish (); Break; } }}
third, adapter mode and other modes of cooperation
In the process of using Android components, each component is more than just a design pattern, and they all come together in a number of design patterns. Individual design patterns are not designed to be practical, scalable components. The application of the two Android adapter modes mentioned above also contains many other design patterns, but we analyze them from a different perspective. Here is my analysis of the above two examples, because there is no deep analysis (the source code of the inheritance chain and the relationship is very complex, only to analyze the surface of a few layers), listed some of the patterns of the combination, of course, there are other patterns, I do not come to the depth of the study, but also temporarily reluctant to delve into.
Adapter + Viewer + Template + Strategy + Combo = baseadapter+listview+ Custom View
Overall UML Diagram
pattern Analysis (different angle of view decision)
Adapter Mode
From a compatibility point of view, then the four methods in Baseadapter (Getitemid (), GetItem (), GetView (), GetCount ()) are adapter methods, They link those uncertain, changeable custom view objects in the ListView and ListView Mosaics. The ListView assembly and initialization only recognizes these four methods, and the adapter will load the view object according to these four methods, respectively, to output the interface and parameters that meet the requirements of the ListView.
Observer Pattern
From the point of view of data update, there is a contact between the Baseadapter and the ListView for the NOTIFIER/observer. Baseadapter is a notifier, and the ListView is an observer. The data collection of the ListView is stored in the Baseadapter, and the Notifydatachanged () method is called whenever the data collection is updated, notifying the ListView to update. At the same time, after the ListView update is complete, you can also call the appropriate method feedback to Baseadapter.
template Mode
From the point of view of the separation between the frame and the invariant, there is a template pattern on the inheritance chain of Baseadapter and ListView. That is, they all have framework parent classes, whereas the framework parent defines the "unchanging" part, and then the application (the category that the programmer inherits) partially implements the "Change" section.
Policy Mode
From the point of view of the change, the application of the strategy pattern in the baseadapter is still present. GetView () is a strategic approach, with different assembly strategies for Different Interface GetView (), but their results and parameters are the same, and it takes on a changing part. We implement different interfaces will inherit baseadapter implementation of different GetView (), is precisely the embodiment of the strategy model.
Combination Mode
From the layout of the custom view itself, a custom view is a combination of different layouts and controls that is a classic representation of the combined pattern, combining the system with our own (or a view of our own implementation) into a new, brilliant view. From this point of view, it has a combination of the application of the pattern.
Adapter + Viewer + template = Service + Activity + custom Service
Overall UML Diagram
pattern Analysis (different angle of view decision)
Adapter Mode
From the point of view of adapter mode, Binder is an adapter class that uses a Transact () interface to fit different objects such as multimedia (MP3, MP4), download tasks, and the client only needs to call Transact (). Incompatible issues with interfaces have been adapted by the binder category.
Observer Pattern
From the point of view of activity and service communication, there is a notifier/observer relationship between service and activity. Service is the notifier and activity is the observer. This can be manifested by the binding service, which, after we call Bindservice (), the service calls the Onbind method to return a IBinder interface after it is bound. A IBinder interface is then returned to the activity client by calling the Onserviceconnect () method in Serviceconnection. Complete the activity and service communication.
template Mode
From the perspective of the change and invariant separation in the framework, there are template patterns in service and activity respectively. Transact () is a template method in service, while Ontransact () is a hook (Kah) method, Callapplicationoncreate is a template method in activity, and OnCreate () is a hook (Kah) method. The part that our program realizes is the card Hayabusa method, and the program framework part is the template method.
Factory mode
From the point of view of object generation, the application of Factory mode is also found in service and activity. For activity, OnCreate () is a factory method that creates the objects that the system needs to run, and for the service, OnCreate () is a factory method that produces binder objects and then returns to the client activity.
Iv. Summary
Adapter mode is a case where the system already exists and is relatively large, suddenly increase the connection between some modules, and the original interface is not in accordance with the circumstances of the use. In Android, the use of adapter mode is familiar to every Android engineer, but in the process of using the adapter, we need to understand the adapter mode mixed with other modes, but also need to understand the reason for the adapter, when the adapter is needed, When not to use the adapter. Moreover, in the same adapter pattern application, there may be other different design pattern ideas, the design pattern is not independent, but mutual infiltration and interdependent.
Android frame design mode (iv)--adapter Method