"Android Source design mode"--Singleton mode

Source: Internet
Author: User

NO1:

Analysis of advantages and disadvantages of lazy single case model

 Public class singleton{    privatestatic  Singleton instance;     Private Singleton () {}          Public Static synchronized Singleton getinstance () {        ifnull) {            new  Singleton ();        }         return instance;}    }

Advantages: The singleton is instantiated only when it is used, saving resources to some extent

Disadvantage: The first time the load needs to be instantiated in a timely manner, the response is slightly slow, the biggest problem is each call getinstance synchronization, resulting in unnecessary synchronization overhead.

So this mode is generally not recommended to use

No2:

Double check Lock (DCL) locking mode

 Public classsingleton{Private StaticSingleton sinstance =NULL; PrivateSingleton () {} Public voiddosomething () {System.out.println ("Do sth."); }         Public StaticSingleton getinstance () {if(Minstance = =NULL){            synchronized(Singleton.class){                if(Minstance = =NULL) {sinstance=NewSingleton (); }            }        }        returnsinstance; }}

Advantages: The Singleton object is instantiated for the first execution of getinstance, and the resource utilization is high. The first layer of instance is designed to avoid unnecessary synchronization, and the second level is to create an instance in null case

Disadvantage: The response is slightly slower the first time it is loaded, and occasionally fails due to the Java memory model. There are also some defects in the high concurrency environment, although the probability of occurrence is very small.

No3:

Static internal class Singleton mode

 Public classsingleton{PrivateSingleton () {} Public StaticSingleton getinstance () {returnsingletonholder.sinstance; }        /*** Static inner class*/    Private Static classsingletonholder{Private Static FinalSingleton sinstance =NewSingleton (); }}

The first call to the GetInstance method causes the virtual machine to load the Singletonholder class, which not only ensures thread safety, but also guarantees uniqueness of singleton objects, and also delays the instantiation of a singleton, so it is recommended to use

No4:

Enumeration single Example

 Public enum singletonenum{    INSTANCE;      Public void dosomething () {        System.out.println ("do sth.") );    }}

Advantage: Thread safety, even if deserialization does not regenerate new instances

NO5:

If you want to prevent a singleton schema object from regenerating when it is deserialized, you must add the readresolve function

 Public Final classSingletonImplementsserializable{Private Static Final LongSerialversionuid = 0L; Private Static FinalSingleton INSTANCE =NewSingleton (); PrivateSingleton () {} Public StaticSingleton getinstance () {returnINSTANCE; }        PrivateObject Readresolve ()throwsobjectstreamexception{returnINSTANCE; }}

That is, the singleton object is returned in the Readresolve method instead of regenerating a new object. And for enumerations, there's no such thing.

NO6:

1) The field type in the Serializable class is not a built-in type for Java, then the field type also needs to implement the Serializable interface

2) If the internal structure of the serializable class is adjusted, such as adding, removing a field, but not modifying Serialversionuid, an exception is thrown. The best scenario is to set the value to 0L, except that the newly modified fields will be 0 or null.

No7:

Using containers to implement Singleton mode

 Public classsingletonmanager{Private StaticMap<string,object> Objmap =NewHashmap<string,object>(); PrivateSingletonmanager () {} Public Static voidRegisterservice (String key,object instance) {if(!Objmap.containskey (Key))        {objmap.put (key,instance); }    }         Public StaticObject GetService (String key) {returnObjmap.get (key); }}

Advantages: can manage a variety of types of singleton, and in use can be achieved through a unified interface to obtain operations, reduce the user's cost of use, but also hidden the specific implementation of the user, reducing the coupling degree.

No8:

Layoutinflater.from (Context) to get layoutinflater services

Context is an abstract class, in application, Activity, service, there will be a context object, that is, the total number of the context of the activity number +service number +1.

An activity entry is the main function of Activitythread.

The implementation class that creates the context object is Contextimpl

No9:

As you can see from part of the code in the Contextimpl class, when a virtual machine loads the class for the first time, it registers various servicefetcher, which contains the Layoutinflater Service. These services are stored in a hashmap in the form of key-value pairs, where the user simply acquires the corresponding servicefetcher based on key, and then obtains the specific service object through the GetService function of the Servicefetcher object. When first fetched, the Servicefetcher's CreateService function is called to create the service object, and then the object is cached in a list, fetched directly from the cache the next time it is fetched, avoiding the repetition of creating objects, thus achieving a singleton effect. System core services exist in singleton form, which reduces resource consumption.

No10:

Layoutinflater is an abstract class, Policymanager is actually a proxy class that implements the Ipolicy interface

The real Layoutinflater implementation class is Phonelayoutinflater

NO11:

The Setcontentview method of activity actually calls the Setcontentview,window of the window is an abstract class, the implementation class is Phonewindow

No12:

CreateView is relatively simple, if there is a prefix, then constructs the full path of the view, loads the class into the virtual machine, obtains the constructor of the class and caches it, creates the view object through the constructor, and finally returns the View object, which is The process of parsing a single view . After parsing the rinflate, the entire tree of views is built.

NO13:

Disadvantages of the singleton pattern :

1) The singleton mode generally has no interface, the extension is very difficult, to expand, in addition to modify the code basically there is no second way to achieve

2) If a single object holds a context, then it is very easy to trigger a memory leak, it is important to note that the context passed to the singleton object is preferably application context

"Android Source design mode"--Singleton mode

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.