Prototype mode of Android source code analysis

Source: Internet
Author: User

definition of a pattern

Use the prototype instance to specify the kind of object to create and create a new object by copying the prototypes.


Usage Scenarios

1, the class initialization needs to digest very many resources, this resource includes the data, the hardware resources and so on, through the prototype copy avoids these consumption;

2, the creation of an object through new requires very tedious data preparation or access permissions, you can use the prototype model;

3, an object needs to be provided to other object access, and each caller may need to modify its value, you can consider using prototype mode to copy multiple objects for the caller to use, that is, a protective copy.


UML class Diagram



Role Description

Client: the user.

Prototype: An abstract class or interface that declares the ability to clone.

Concreteprototype: The specific prototype class.


Simple Example

Let's take a simple document copy as an example to illustrate the simple prototype pattern pattern.

Package Com.dp.example.builder;package Com.dp.example.prototype;import Java.util.arraylist;import java.util.List;/ * * Document type, playing Concreteprototype role, while cloneable is representing prototype role * * @author mrsimple */public class Worddocument implements C    loneable {/** * text * */private String mText; /** * Image list */private arraylist<string>
  
   Mimages = new Arraylist<string>
   
    
();    Public worddocument () {System.out.println ("-----------Worddocument constructor-----------"); }/** * Clone Object */@Override protected worddocument Clone () {try {worddocument doc = (Wo            rddocument) Super.clone ();            Doc.mtext = This.mtext;            Doc.mimages = this.mimages;        return doc;    } catch (Exception e) {} return null;    } public String GetText () {return mText;    } public void SetText (String mText) {this.mtext = MText; } public List
    
     
      getimages () {return mimages;    }/** * @param img */public void AddImage (String img) {this.mImages.add (IMG); }/** * Print document Contents */public void showdocument () {System.out.println ("-----------Word content Start---        --------");        System.out.println ("Text:" + mText);        System.out.println ("Images List:");        for (String imgname:mimages) {System.out.println ("image name:" + imgname);    } System.out.println ("-----------Word Content End-----------"); }}

     
    
   
  

the worddocument class simulates the basic elements in a Word document, namely text and pictures. Worddocument's role in the prototype pattern example is Concreteprototype, while Cloneable's role is prototype. Worddocument implements the Clone method to implement object cloning. Let's look at the use of the client side:

public class Client {public    static void Main (string[] args) {        worddocument origindoc = new Worddocument ();        Origindoc.settext ("This is a document");        Origindoc.addimage ("Picture 1");        Origindoc.addimage ("Picture 2");        Origindoc.addimage ("Picture 3");        Origindoc.showdocument ();        Worddocument doc2 = Origindoc.clone ();        Doc2.showdocument ();                Doc2.settext ("This is a modified Doc2 text");        Doc2.showdocument ();                 Origindoc.showdocument ();    }}

The output results are as follows:


As you can see, DOC2 is created by Origindoc.clone (), and doc2 the first output is the same as the Origindoc output. That is, DOC2 is a copy of Origindoc, their content is the same, and doc2 modified the text content will not affect the Origindoc text content. It is important to note that the constructor is not executed when copying objects through clone!

Shallow copy and deep copy

Modify the contents of the main function to read as follows:

    public static void Main (string[] args) {        worddocument origindoc = new Worddocument ();        Origindoc.settext ("This is a document");        Origindoc.addimage ("Picture 1");        Origindoc.addimage ("Picture 2");        Origindoc.addimage ("Picture 3");        Origindoc.showdocument ();        Worddocument doc2 = Origindoc.clone ();                Doc2.showdocument ();                Doc2.settext ("This is a modified Doc2 text");        Doc2.addimage ("haha. jpg");        Doc2.showdocument ();                Origindoc.showdocument ();    }

The output results are as follows:


The attentive friend may have found, in Doc2 added a picture called "haha. jpg", but also show in Origindoc?  What's going on here? In fact, friends who have studied C + + know that this is because the Worddocument clone method above is simply a shallow copy, the reference type of the new object Doc2 Mimages simply point to the this.mimages reference, and did not copy. Doc2 Mimages added a new picture, in fact, to Origindoc added a new picture, so origindoc inside also has "haha. jpg".  So how do we solve this problem? It is the use of deep copy, that is, when copying objects, the reference type of the field should also be in the form of a copy, rather than simply quoted form. Examples are as follows:

    /**     * Clone Object */    @Override    protected Worddocument Clone () {        try {            worddocument doc = ( worddocument) Super.clone ();            Doc.mtext = this.mtext;//            doc.mimages = this.mimages;            Doc.mimages = (arraylist<string>) this.mImages.clone ();            return doc;        } catch (Exception e) {        }        return null;    }
As shown in the code above, Doc.mimages points to a copy of This.mimages instead of the this.mimages itself, so that when you add a picture doc2 it does not affect Origindoc:



Source Analysis

In the Android source code, we use the familiar intent to analyze the prototype pattern in the source code. A simple example is as follows:

                Uri uri = uri.parse ("smsto:0800000123");                        Intent shareintent = new Intent (intent.action_sendto, URI);                        Shareintent.putextra ("Sms_body", "The SMS Text");                                            Intent Intent = (Intent) shareintent.clone ();                    StartActivity (Intent);

The results are as follows:


as you can see, we copied an object intent through the Shareintent.clone method, then executed startactivity (intent), and then entered the SMS page with the number 0800000123, the text content is The SMS text, that is, these content are consistent with shareintent.


Now let's look at the implementation of Intent's clone:

    @Override Public    Object Clone () {        return new Intent (this);    }    /**     * Copy constructor.     *    /Public Intent (Intent o) {        this.maction = o.maction;        This.mdata = O.mdata;        This.mtype = O.mtype;        This.mpackage = O.mpackage;        This.mcomponent = o.mcomponent;        This.mflags = o.mflags;        if (o.mcategories! = null) {            this.mcategories = new arrayset<string> (o.mcategories);        }        if (O.mextras! = null) {            This.mextras = new Bundle (O.mextras);        }        if (o.msourcebounds! = null) {            this.msourcebounds = new Rect (o.msourcebounds);        }        if (o.mselector! = null) {            this.mselector = new Intent (o.mselector);        }        if (o.mclipdata! = null) {            this.mclipdata = new Clipdata (o.mclipdata);}    }

As you can see, the Clone method actually calls the new Intent (this) internally, which is exactly the same as the copy constructor in C + + and is a deep copy. Because this mode is relatively simple, do not make too many instructions.


Advantages and Disadvantages Advantages:1, prototype mode is a copy of the memory binary stream, than the direct new one object performance much better, especially in a loop to produce a large number of objects, prototype mode can better reflect its advantages.
Disadvantages:1.This is both its advantages and disadvantages, directly in memory copy, the constructor will not be executed, in the actual development should pay attention to this potential problem. The advantage is to reduce the constraints, the disadvantage is to reduce the constraints, need everyone in the actual application of consideration.

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.