Android Common design mode (i)

Source: Internet
Author: User

Due to the frequent changes in the project, as a programmer, we need to master the need for design patterns, it goes without saying ~ ~, the following are some of my own study of the design pattern summary.
Next, mainly for several more commonly used models to explain, mainly the following several:

    • Observer pattern
    • Adapter mode
    • Proxy mode
    • Factory mode
    • Single-Case mode
    • Command mode

1. Observer mode (Observer pattern)
EXPLANATION : The Observer pattern defines a one-to-many dependency that allows multiple observer objects to listen to a Subject object at the same time, and notifies all observer objects when the subject object changes state, enabling them to automatically update themselves.
The Story understands : The Observer wants to know the company all mm situation, as long as joins the company's MM intelligence mail group to be OK, Tom collects the intelligence, when discovers the new intelligence, does not have one to inform us, publishes directly to the Mail group, we as the Subscriber (Observer) can receive the intelligence in time.
Common examples : 1. Baseadapter.registerdatasetobserver and Baseadapter.unregisterdatasetobserver two method to register to Baseadater, unregister a datasetobserver ; 2. Use Contentobserver to monitor database changes.
Application Scenario : 1. When a change to an object needs to change other objects at the same time without knowing how many objects need to be changed; 2. When an object must notify other objects, it cannot assume who the other objects are.

The observer pattern consists of 2 objects, the observer and the Observer, in which observable represents the observer, an abstract class that can only be inherited. Observer represents the observer, he is an interface, so the observer can have multiple, the class that implements the interface belongs to the Observer.
This is a vivid and detailed demo on the Web:
Observed by:

 Public  class myperson extends Observable {    Private intAgePrivateString name;PrivateString sax; Public int Getage() {returnAge } Public void Setage(intAge) { This. Age = Age;        Setchanged ();    Notifyobservers (); } PublicStringGetName() {returnName } Public void SetName(String name) { This. name = name;        Setchanged ();    Notifyobservers (); } PublicStringGetsax() {returnSax } Public void Setsax(String sax) { This. Sax = sax; }@Override     PublicStringtoString() {return "MyPerson [age="+ Age +", name="+ name +", sax="+ sax +"]"; }}

MyPerson is the Observer, the class calls the Setchange () and the Notifyobservers () two methods, the former is to inform the data changes, the latter is to send a signal to notify the observer.

Observed by:

 Public  class myobserver implements Observer {    Private intIPrivateMyPerson MyPerson;//Observed objects     Public Myobserver(inti) {System.out.println ("I am the Observer---->"+ i); This. i = i; } Public int Geti() {returnI } Public void SetI(inti) { This. i = i; } PublicMyPersonGetmyperson() {returnMyPerson; } Public void Setmyperson(MyPerson MyPerson) { This. MyPerson = MyPerson; }@Override     Public void Update(Observable Observable, Object data) {System.out.println ("Viewer---->"+ i +"Get Updated!" "); This. MyPerson = (MyPerson) observable;    System.out.println (((MyPerson) observable). ToString ()); }}

The observer needs to implement the observer interface, where there is only one update method, which is executed when the observer receives a notification signal from the observer.

Specific demo source and implementation of the effect can point connection

2. Adapter mode (Adapter pattern)
Interpretation: The interface of a class is transformed into another interface that the client expects, so that two classes that are not able to work together because of an interface cause mismatch can work together. The adaptation class can return an appropriate instance to the client based on the parameters.
Story Understanding: met a beautiful Sarah at a friend's party, from Hong Kong, but I do not speak Cantonese, she can not speak Mandarin, had to resort to my friend Kent, he as my adapter between Sarah, let me and Sarah to talk to each other ( I do not know whether he will play with me).
Common Example : ListView is used to display list data, but as a list data collection there are many forms, there are arrays, there are cursor, we need the corresponding adapter as a bridge, processing the corresponding data (and can form the view that the ListView needs).
Application Scenario : 1. The interface of the business is incompatible with the class of work (e.g., some methods of implementing an interface are missing from the class) but need to work together; 2. Provides interfaces for new business requirements on the basis of existing interfaces and classes.

The adapter mode is divided into class adapter mode and object adapter mode. About the class adaptation mode, because Java's single inheritance, so when a class has been inherited, the other is only the interface, you need to implement the appropriate method manually, so that the client can create any kind of sub-class to meet the requirements to achieve specific functionality. Another type of object adapter, which is not a way to use inheritance, is to use a direct association, or a delegate, that details the adapter mode (Adapter): Class Adapter, Object adapter

The next step is to use the ListView and Arrayadapter to explain
ListAdapter:

publicinterface ListAdapter {    publicintgetCount();    Object getItem(int position);    long getItemId(int position);    View getView(int position, View convertView, ViewGroup parent);    boolean isEmpty();}

The ListView as a client, the desired target interface is ListAdapter, contains GetCount (), GetItem (), GetView () and several other methods, in order to be compatible with list< T > Data type data source, Specifically defines the Arrayadapter adapter, which is, in plain view, a compatible modification of the data source for the target interface.

Abstract class Baseadapter, omitting other code, here are only two methods listed:

public   Abstract  class   Baseadapter  implements  listadapter ,    Span class= "Hljs-title" >spinneradapter  { //...  public  View getdropdownview  (int  position, view    Convertview, ViewGroup parent) {return  getView (position, convertview, parent); } public  boolean      IsEmpty  () {return  getcount () = = 0 ; }}

Arrayadapter list< T > is encapsulated into a listadapter implementation that satisfies the call of the ListView:

 Public  class arrayadapter<T> extends baseadapter implements  filterable {    PrivateList<t> mobjects;//I'm just going to list this one constructor, and you know what that means.     PublicArrayadapter (Context context,intTextviewresourceid, t[] objects) {init (context, Textviewresourceid,0, Arrays.aslist (objects)); }Private voidInit (Context context,intResourceintTextviewresourceid, list<t> objects) {mcontext = context;        Minflater = (layoutinflater) context.getsystemservice (Context.layout_inflater_service);        Mresource = Mdropdownresource = resource; Mobjects = objects;//Reference object, also expresses the meaning that the combination is better than the inheritanceMfieldid = Textviewresourceid; } Public intGetCount () {returnMobjects.size (); } PublicT GetItem (intPosition) {returnMobjects.get (position); } PublicView GetView (intPosition, View Convertview, ViewGroup parent) {returnCreateviewfromresource (position, Convertview, parent, mresource); }// ... ...}

We were so successful that list< T > as a data source was passed to the ListView as the target interface the ListView wanted. This is actually one of the object adapters.

3. Agent mode (proxy pattern)
Interpretation: by introducing a new object to the operation of a real object or a new object as an alias for a real object, the implementation mechanism is the proxy pattern (providing a proxy for other objects to control access to the object).
The story understands: The campus agent is for his corresponding boss acting, and this campus agent's job is to visit the students on campus, such as the student questionnaire and so on. The student is the other object of the official statement, the campus agent's supervisor controls the student's visit by controlling the campus agent.
Common Example : Activitymanagerproxy class is a proxy, it is the agent of Activitymanagernative, that is to say Activitymanagerproxy is the proxy class, And activitymanagernative is equivalent to the "Boss role" class, they all have a common interface Iactivitymanager. Activitymanager, which is equivalent to proxy mode client. In this class, you can see a large number of getxxx functions, which are called to the Getdefault () method of the Activitymanagernative class, and the method obtains a common singleton iactivitymanager reference. The implementation in the proxy is then invoked through polymorphism
applicable scenario : The application of proxy mode is divided into several types: remote agents, virtual agents, security agents, etc., specifically for others to do wedding clothes-agent mode

Take a look at the chart below (a detailed and vivid example of what you see on the Web):

Subject class: Defines the common interface of realsubject and proxy, so that you can use proxy in any place where realsubject is used.
Realsubject class: Defines the real entity represented by the proxy.
Proxy class: Saving a reference allows the agent to access the entity and provides an interface with the same interface as the subject, so that the proxy can be used instead of the entity.

Next, let's implement the pattern:
Category 1.Subject: Image.java

/** * Subject类 */publicabstractclass Image {    publicabstractvoiddisplayImage();}

Category 2.RealSubject: Realimage.java

ImportCom.andyidea.patterns.subject.Image;/** * Realsubject class * *   Public  class realimage extends Image {      PrivateString filename; Public Realimage(String filename) { This. filename = filename;      Loadimagefromdisk (); }Private void Loadimagefromdisk() {System.out.println ("Loading"+ filename); }@Override       Public void DisplayImage() {System.out.println ("Displaying"+ filename); }  }

Category 3.proxy: Proxyimage.java

ImportCom.andyidea.patterns.realsubject.RealImage;ImportCom.andyidea.patterns.subject.Image;/** * Proxy class * / Public  class proxyimage extends Image {    PrivateString filename;PrivateImage Image; Public Proxyimage(String filename) { This. filename = filename; }@Override     Public void DisplayImage() {if(Image = =NULL) {image =NewRealimage (filename);    } image.displayimage (); }}

4. Client Test class: Proxyclient.java

ImportCom.andyidea.patterns.proxy.ProxyImage;ImportCom.andyidea.patterns.subject.Image;/** * Proxy mode Client Test class */ Public  class proxyclient {     Public Static void Main(string[] args) {System.out.println ("Welcome to my blog!"+"\ n"+"Proxy Patterns."+"\ n"+"-------------------------------"); Image MImage1 =NewProxyimage ("My.image1"); Image MImage2 =NewProxyimage ("My.image2");        Mimage1.displayimage ();    Mimage2.displayimage (); }}

The results of the operation are as follows:

        Welcome to my Blog!          Proxy Patterns        -------------------------------         Loading   My.Image1         Displaying My.Image1         Loading   My.Image2          Displaying My.Image2

In summary, the proxy class is to save a reference to the entity, but also implement the entity-like interface method, so that you can replace the entity!!

The above is the Observer mode, adapter mode, proxy mode of understanding, the next will be in the common Android design mode (ii), continue to the remaining three modes of elaboration.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android Common design mode (i)

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.