Android design mode single case mode (Singleton pattern)

Source: Internet
Author: User

Personal Summary study and research, part of the content reference "Android source design mode analysis and actual combat" a book ~ ~. Definition: Ensure that a class has only one instance, and instantiate it itself and provide it to the entire system.       In other words, the Singleton must satisfy 3 points: 1, the Singleton class can have only one instance. 2, the Singleton class must create its own unique instance.       (The constructor is privatized to prevent external programs from being constructed with new). 3. The Singleton class must provide this instance to other objects. (Exposes a public static method or returns a singleton class object through an enumeration).
Two. Usage scenario: Make sure that a class has and has only one object in the scene, to avoid producing multiple objects that consume too much resources. For example, in an application, there should be only one Imageloader instance, this imageloader contains thread pool, cache system, network request, etc., and consumes resources more. For example, to access resources such as IO and databases, consider using singleton mode. Android source code also has a lot of places with a singleton mode, such as Input Method manager Inputmethodmanager, such as an application only a Application object. Three. Implementation mode: 1, a hungry man style single case characteristics: Static objects are initialized when the static object, no longer change, is inherently thread-safe. Cons: Consuming resources.
public class Singleton {    private static Singleton instance = new Singleton ();    Private Singleton () {    } public    static Singleton getinstance () {        Retun instance;    }}
2, lazy-type Singleton features: declares a static object and initializes it the first time you call getinstance. Advantage: Lazy Loading. Cons: Thread is unsafe.
public class Singleton {        private static Singleton instance = null;    Private Singleton () {    } public    static Singleton getinstance () {        if (instance = = null) {            instatnce = new S Ingleton ();        }        return instance;}    }
Lazy lock getinstance () static method adds the Synchronized keyword, which means that the synchronization method guarantees thread safety. Cons: Causes unnecessary synchronization overhead. The specific code is as follows:
public class Singleton {        private static Singleton instance = null;    Private Singleton () {    } public    static synchronized Singleton getinstance () {        if (instance = = null) {            Instatnce = new Singleton ();        }        return instance;}    }
3, double check lock (double checklock) to achieve a single case features: delayed loading, resolved redundant synchronization, thread safety. Two times empty, the first layer is to avoid unnecessary synchronization. The second layer is to create an instance in case of instance null.  
public class Singleton {       private static Singleton instance = null;        Private Singleton {    } public        static Singleton getinstance () {        //If already initialized, no need to get lock Everytime.        if (instance = = null) {            synchronized (singleton.class) {                if (instance = = null) {                    instance = new Singleton (); 
   }}}        return instance;    }}

  

4, static internal class single case features: delayed loading, thread safety. Using the Java Virtual machine load class features for lazy loading and thread safety, the recommended single implementation approach.
public class Singleton () {    private Singleton () {    } public        static Singleton getinstance () {        return single tonholder.instance;    }        /**     * Static inner class, the singleton object is created only when the inner class is loaded */    private static class Singletonholder {         private static final Singleton instance = new Singleton ();}    }
5, enumeration features: Simple, simple threading, deserialization will not re-create the object. (in the previous four cases, a new instance is generated in the deserialization). The enumeration singleton is recommended in effective Java, but it is not recommended on Android platforms. The official Android training course clearly states: Enums ofter require more than twice as much memory as static constants. You should strictly avoid using enums on Android.
public enum Singleton {    //defines an enumerated element, which is an instance of Singleton     INSTANCE;    public void Dosomethig () {        //TODO:    }}
Enumerations are like normal classes in Java, and can have their own methods as well as fields.  Most importantly, the creation of the default enumeration instance is thread-safe and is, in any case, a single case. Here's how to use it:
Singleton Singleton = singleton.instance;singleton.dosomething ();
6, using the container to achieve a single case of brain hole open, and then to see an alternative way of implementation. Maintain a unified management class, inject a variety of singleton types, and, when used, get the corresponding type of singleton object according to key.
public class Singletonmanager {        private static map<string, object> objmap = new hashmap<> ();    Private Singleton () {    } public        static void Addsingleton (String key, Object instance) {        if (! Objmap.containskey (key)) {            objmap.put (key, instance);        }    }    public static Getsingleton (String key) {        return objmap.get (key);}    }

  

Summary: The choice of implementation depends on the project itself, such as whether it is a complex concurrency environment, whether the JDK version is too low, the resource consumption of the Singleton object, and so on. In general, clients typically do not have high concurrency, so it is not too much to choose which one to implement. Individuals generally use static inner classes to implement them. Note: If a singleton object holds a context, it is easy to trigger a memory leak, and it is important to note that the context passed to the singleton object is preferably application context.

Android design mode single case mode (Singleton pattern)

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.