Android often uses design mode (i)

Source: Internet
Author: User

Due to the frequent changes in the project, as a procedural ape, we need to master the need for design patterns. is self-evident ~ ~. Here is a summary of some of the design patterns I have studied myself.
Next, mainly for a few more frequent use of the model 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 when the subject object changes in state, all the observer objects are notified so that they can proactively update themselves.
The Story understands : The Observer wants to know the company all mm situation, only must increase the company's mm intelligence mail group to be able, Tom collects the intelligence, when discovers the new intelligence, does not have one to inform us, directly publishes to the mail group. We as Subscribers (observers) are able to receive information in a timely manner.
Common examples : 1. Baseadapter.registerdatasetobserver and Baseadapter.unregisterdatasetobserver two ways to register with Baseadater, write off 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, it is not known how many objects need to be changed. 2. When an object must notify other objects. And it cannot assume that other objects are who.

The observer pattern consists of 2 objects, the observer and the Observer. In this mode. Observable represents the observer, and this object is an abstract class. can only be inherited. Observer represents the observer, he is an interface. So the observer can have more than one. The class that implements the interface belongs to the Observer.
This is a vivid and careful 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 signals to inform 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. When the Observer receives (the observer) a notification signal. The action will be executed.

Detailed demo source code and implementation of the effect can point connection

2. Adapter mode (Adapter pattern)
Explanation: transforming a class's interface into what the client expects is an interface that can work together with two classes that would otherwise not be able to work together because of an interface mismatch.

The adaptive class can return a suitable instance to the client based on the number of references.


Story Understanding: met a beautiful Sarah at a friend's party. From Hong Kong, but I don't speak Cantonese. She could not speak Mandarin, only to turn to my friend Kent, who, as a adapter between Sarah and I, allowed me and Sarah to talk to each other (and not know if he would play with me).
Common Instances : ListView is used to display list data, but there are many forms of data collections as lists. With an array, with the cursor, we need the appropriate adapter as a bridge to process the corresponding data (and to form the view required by the ListView).
Application Scenario : 1. The interface of the business is incompatible with the class of work, (for example: some methods of implementing an interface are missing from the class) but need to work together. 2. Provide 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 class adaptation mode. Because of the single inheritance of Java, when a class has been inherited. The other is only the interface, you need to implement the corresponding method manually, so that in the client can create any kind of sub-class to meet the requirements. To achieve detailed functionality. And the second object adapter, which is not using inheritance to implement again, but using a direct association, or a way of entrusting, detailed visibility of the blog details the adapter mode (Adapter): Class Adapter, Object adapter

Next, we'll use the ListView and Arrayadapter to solve the
ListAdapter:

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

ListView as a client, the required target interface is listadapter, including GetCount (), GetItem (), GetView () and several other methods. To be compatible with data sources of list< T > Data types. Specifically defined the Arrayadapter adapter, plainly. is to modify the data source to be compatible with the target interface.

Abstract class Baseadapter, omitting other code, here are just a list of two methods:

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 listing this one constructor. 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 as a surrogate for a real object, this 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 students on campus. For example, a questionnaire or something about a student.

The student is the other object of the official statement, the campus agent's supervisor controls the student's access by controlling the campus agent.
Common Example : The 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. It is equivalent to the client of proxy mode. 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 agent, virtual agent, security agent, etc., in detail for others to do wedding clothes-agent mode

Take a look at one of the following charts (a carefully vivid example seen on the Web):

Subject class: Defines the common interface of realsubject and proxy, so that you can use proxy wherever you use Realsubject.
Realsubject class: Defines the real entity represented by the proxy.
Proxy class: Saving a reference allows the agent to access the entity and provide the same interface as the subject interface. This allows proxies to be used instead of entities.

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 execution are as follows:

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

In summary, a proxy class is a reference to an entity. At the same time the entity-like interface method is implemented, so. will be able to replace the entity!!

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

Android often uses 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.