Singleton and Android

Source: Internet
Author: User

Singleton (Singleton)

One, What is a singleton mode

Singleton mode. The simple point is to design a class to have at most one instance at any time, and provide a global access point to the instance.


Second, Why single Case

In very many places in the program. It is very important to have just one instance. For example, in Windows. The Task Manager has only one. No matter how many times you click to open Task Manager, Task Manager will simply generate a form. For example, in some software, the toolbox is unique, no matter how many times you click to open the Toolbox. The toolbox is just one.

Why design it like this? Because of a program like Task Manager or Toolbox, just having one is enough to complete all the work. Many programs only consume system resources in vain, and programs such as Task Manager introduce synchronization issues between multiple task managers. So for some of these programs. It is necessary to have only one instance or program.


Third, Why do I need a singleton mode

As mentioned above for some programs. It is necessary to keep only one instance of it, but how do you ensure that a program or a class has only one instance? The following is explained from the perspective of the class.

The first method. Let's put aside the concept of design patterns, assuming you didn't know it at all. What do you do in the face of this design requirement? We are able to use a global class pointer variable with an initial value of NULL. Whenever you need to create an object of the class, check that the pointer is null. If NULL, a new object is created using new, and the pointer to the object is assigned to the global pointer variable.

If the pointer is not NULL. Returns the pointer directly or uses the pointer.

This is probably the easiest way to think about it.

Another way is to use a singleton pattern. Singleton mode blocks generic instantiation by maintaining a pointer inside the class that points to the inside of the class and declaring its constructor as private or protected. Instead, a static public member function is used to implement and control the instantiation of the class.

In the static public member function, infer whether the static member pointer of the class is null if it is null. , a new instance is created. and point the static member pointer of the class to the implementation. If the static member pointer is not NULL, NULL is returned directly.

If the view is not very clear, it does not matter, see the following class diagram and code will be clear.

In contrast, the other method is better than the first one. First of all. The first approach does not force a class to have only one instance, and all control is in fact in the user's design. The other is that the designer of the class does it well, and it doesn't matter to the user.

In other words, assuming that the first approach is used, only the user is willing to do so. This class can have countless instances, and for another method. It can only have one instance, regardless of whether you want to use it or not. It's like we're going to eat, the first way we need customers to infer which dishes are sold out. Another method is that the restaurant infers which dishes have been sold out, apparently in life, another way is reasonable.


Four, class diagram of a singleton pattern



Five, implementation of the Singleton pattern (C + + implementation)

1 , Singleton.h , define the basic members and interfaces of the class

#ifndef Singleton_h_include#define Singleton_h_include class singleton{public    :       static singleton* GetInstance ();       Voidreleaseinstance ();     Private://function       Singleton () {}       ~singleton () {}     private://data       static singleton*_instance;       static unsigned int_used;}; #endif

2 , Singleton.cpp . Implement getinstance method and releaseinstance method

#include "Singleton.h" singleton* singleton::_instance (0); unsigned int singleton::_used (0); singleton* singleton::getinstance () {    ++_used;    if (_instance = = 0)    {       _instance = Newsingleton ();    }    return _instance;} void Singleton::releaseinstance () {    --_used;    if (_used = = 0)    {       delete _instance;       _instance = 0;    }}

Code Analysis:

From the above class diagram and code implementation can be seen. In the singleton mode. We have declared the class's constructor private, which prevents the instantiation of the object outside the class. Since objects cannot be instantiated outside of a class, how do we instantiate the class? We know that static members exist with classes. Does not exist with the object, so we use a public static function, which is responsible for implementing the object of that class. Since the static function is a member function of the class, it is able to access the private constructor of the class, which is what we mentioned earlier as the global access point.


Since there may be multiple objects that reference the object of the Singleton class, and there is only one, there must be multiple pointer variables pointing to the same piece of memory in the heap, and if one of the pointers deletes the heap memory, the other pointers do not know that the object it refers to does not already exist. A segment error must occur to continue referencing the object in order to prevent the call to delete outside of the class. In this case, the destructor is declared as private, which makes it illegal to delete a pointer to the singleton class object outside the class.


But the C + + heap memory is managed entirely by the program ape, assuming it cannot be delete. The object is always present in the heap memory, so a method releaseinstance and reference count are introduced here, and when the object is no longer needed, the ReleaseInstance method is called, which will subtract the reference count by 1, freeing the object when all the code does not need it , that is, when the reference count is 0 o'clock, the object is disposed.


Six, a singleton mode under multi-threading

The above code can cause problems in a multithreaded environment. Give me a sample example. is when two threads call the getinstance function at the same time. If the class has not yet been instantiated, the two thread reads the _instance to 0. Then two threads will be new to the object, so that the class has two instances. At the same time, the same problem will exist for _used operations, where _use is 1.

Therefore, it is obvious that the design is unsafe under multi-threading.

In order to solve the above problems, we need to ask locking for _instance and _used in the functions getinstance and releaseinstance.

For simplicity. Just list some of the key codes. The changed code is as follows: (source files are singlton_thread.h and singleton_thread.cpp)

Pthread_mutex_tsingleton::_mutex (Pthread_mutex_initializer); singleton* singleton::getinstance () {    pthread_mutex_lock (&_mutex);    ++_used;    if (_instance== 0)    {       _instance= new Singleton ();    }    Pthread_mutex_unlock (&_mutex);    Return_instance;} void Singleton::releaseinstance () {    pthread_mutex_lock (&_mutex);    --_used;    if (_used== 0)    {       delete_instance;       _instance= 0;    }    Pthread_mutex_unlock (&_mutex);}

Code Analysis:

As can be seen from the above code, each request to invoke the Get/releaseinstance function will be locked and unlocked, and lock and unlock is a more time-consuming operation, so the above-mentioned code efficiency is actually not high.

In some design patterns of the book, you will see the use of double if inference to solve the problem of multiple locks, but this method is unrealistic here, because this method does not solve the _used interview problem. Other words. Even access to _instance can use a double if statement to greatly reduce the lock and unlock operation. However, the _used + + and--operation of the same need to be locked. And those books are able to use the double if to solve the problem. is determined by the language used, such as using Java or C #, they do not need to manage memory, so there is no reference count _used in the code above, so the double if method can work.

If you want to implement double if inference in C + +, you do not use reference counting to manage memory. That is, once an object has been allocated, it exists in heap memory.

There is no reference counting problem with C + + at this point. There is no need to release memory, so there is no need for the ReleaseInstance method above.

The implementation of its GetInstance method is as follows:

singleton* singleton::getinstance () {if (_instance = = 0) {pthread_mutex_lock (&_mutex); if (_instance = = 0) _instance = New Singleton ();p thread_mutex_unlock (&_mutex);} return _instance;}


This makes it possible to simply lock and unlock once, greatly improving time efficiency. However, once the object allocates memory, the memory is not freed. So which implementation strategy to use in C + + depends on your choice of time and space. If time is more important. The latter method is used, if space is more important, the former method is used.


Seven, Android a singleton mode in

There are a large number of singleton classes in Android, such as: Inputmethodmanager class, Calendardatabasehelper class, editable class, and so on. In these classes, there is a method getinstance, in which the method either returns the object's reference directly or infers whether a reference to a class is null. If it is not NULL, the reference is returned directly and, if NULL, a new object is returned. Like what. For the Calendardatabasehelper class, there is code such as the following:

public static synchronized Calendardatabasehelper getinstance (contextcontext) {    if (Ssingleton = = null)    {       Ssingleton = Newcalendardatabasehelper (context);    }        return Ssingleton;}

From the code here, it can be seen that the actual mode is very similar to what is said above, but because Java does not use the program ape itself to manage memory, it does not need a reference count, and the method is public static. The synchronized is to ensure that only one thread can enter the method at the same time, which is to prevent the 6th one from the above-mentioned security problem in multi-threaded mode.


Eight, Source Address

C + + Source Address:http://download.csdn.net/detail/ljianhui/7464147


Copyright notice: This article blog original article. Blogs, without consent, may not be reproduced.

Singleton and Android

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.