First, we understand some of the concepts of singleton patterns.
确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例。
There are several advantages to doing this:
- For those classes that consume more memory, only one instantiation can greatly improve performance, especially in mobile development.
- There is always only one instance in memory when you keep the program running
In fact, there are many ways to achieve a single case, but individuals tend to have more than 1 of them. You can see the singleton mode
The code is as follows
public class Singleton { private static volatile Singleton instance = null; private Singleton(){ } public static Singleton getInstance() { if (instance == null) { synchronized (Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; }}
To ensure a single case, you need to do a few steps
- You must prevent external calls to the constructor to instantiate, so the constructor must be privatized.
- You must define a static function to obtain the singleton
- Single case using volatile modifiers
- Using synchronized for synchronous processing, and double-judging whether it is null, we see that synchronized (Singleton.class) is also null-judged, because one thread enters the code, and if another thread waits , when the previous thread has created an instance, and the other thread gets the lock into the synchronization code, the instance already exists and there is no need to create it again, so the decision is null or necessary.
In Android, a single case is used in many places. such as the single case in Eventbus
private static volatile EventBus defaultInstance;public static EventBus getDefault() { if (defaultInstance == null) { synchronized (EventBus.class) { if (defaultInstance == null) { defaultInstance = new EventBus(); } } } return defaultInstance;}
Common design Patterns in Android development (i)--Singleton mode