Android design mode single case mode Singleton

Source: Internet
Author: User

I. Overview

The singleton pattern is the simplest of the design patterns, but it does not have an abstract relationship between the various objects in the design pattern, so some people don't think of it as a pattern, but as an implementation technique. The singleton pattern, like the literal meaning, provides an instance that can only be instantiated by itself. and provides a global access point. To meet these requirements is three points: a private constructor (to prevent being instantiated by others), a static private object (to provide an instance), a static public getinstance method (used to create and get an instance object).
Advantages and Disadvantages:Singleton allows you to create only one instance, without frequent creation and destruction, which saves memory and speeds up access to objects.However, there are no abstract layers and excuses, which are not easy to expand. The singleton provides both a factory approach and a business approach, partly contrary to the principle of single responsibility
two. Single Instance implementation

The implementation of the Singleton has two main ways, namely lazy mode and a hungry man mode, they have different time and efficiency of instantiation.


1. Lazy mode

/** * Created by Jesse on 15-6-28. */public class Singleton {    private static Singleton instance;    Private Singleton () {}//must have a proprietary structure, or talk about a singleton public    static Singleton getinstance () {        if (null = = instance) {            Instance = new Singleton ();        }        return instance;}    }


Lazy Mode when an external object gets an instance every time it is initialized, this is a bit more efficient than the A Hungry man mode, but it saves some space, because when the instance is used to initialize, if it is not used, This object is not constructed in lazy mode. This is equivalent to using space for time. That is, lazy loading technology. It is also important to note that there must be a private construct, or else an external object can instantiate the object, and then a single example is discussed .


This time a lot of little friends to say, you lazy single case has a problem, the thread security problem. Of course, this approach is not secure, when two threads A and b concurrency to obtain the instance, instance has not been initialized, assuming a first get the time slice to initialize the instance, When the instance has not been initialized, the time chip to B, then because instance has not been initialized to complete so instance is still empty, so B will also go to instance instantiation once, The end result is that instance was instantiated two times. This can have serious consequences, the solution is locking (sacrificing some performance), using a hungry man mode.


To GetInstance method lock, this locking method can solve the problem of thread safety, but every time the external object to get the instance of the thread lock, and then also to determine whether the instance is instantiated, so that in the case of high concurrency of multithreading, the loss of efficiency is considerable.

public class Singleton {    private static Singleton instance;    Private Singleton () {} public     static synchronized Singleton getinstance () {//Add lock to GetInstance method        if (null = = Instance) {            instance = new Singleton ();        }        return instance;}    }

later, a double-lock instance is extended, which is locked only at the time of the first instantiation, and determines whether or not it is instantiated before and after the lock is added. Performance is better than single lock. But this double lock also encounters a problem, Errors can occur on different platforms or under different compilers. Mainly because some compilers optimize the process of new Singleton (), assuming that thread AB gets the instance concurrently, and that in some compilers there may be a thread instantiation instance, When the system has allocated instance to memory, but has not initialized the instance member variable, the time slice to the B process, when the instance is not NULL, B directly take the instance to operate the member variable, but this time the member variable has not been initialized, The result may be crash. When encountering this compiler problem, it is necessary to add a volatile modifier to the instance variable, eliminating the interference of compiler optimizations.

public class Singleton {    private static Singleton instance;    Private static volatile Singleton instance; Use    private Singleton () {} public    static Singleton getinstance () {        if (null = = instance)            When encountering a compiler problem { Synchronized (singleton.class) {                if (null = = Instance)                    instance = new Singleton ();}        }        return instance;}    }


2. A Hungry man mode


A hungry man mode is the operation of the system, in the class when the initialization of operations, external objects do not need to make any judgment can be used directly, from the efficiency is better than the lazy mode. However, the lazy loading technique is compared with the idle mode, regardless of the system's use of this instance, The memory will be created at the very beginning. In the opposite direction, the A hungry man is space-changing time.

public class Singleton {    private static final Singleton instance = new Singleton ();    Private Singleton () {}//must have a privately constructed structure, or talk about a singleton public    static Singleton getinstance () {        return instance;    }}

Three. Summary
according to the above analysis, it is clear that the A hungry man mode does not have to face the problem of thread concurrency. And the A Hungry man mode is better than the lazy mode from the call speed and response time. But the lazy model is better than the A hungry man mode in terms of resource utilization.
Reprint Please specify Source: http://blog.csdn.net/l2show/article/details/46672061

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

Single-case mode for Android design mode Singleton

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.