Design Mode in Android-singleton Mode
Design Mode in Android-singleton Mode
The Singleton mode is a common mode. in Java, if you want a JVM to have only one instance of a class, you need to use the singleton mode, the requirement for only one instance is generally as follows:
1. The object instance is large and complex, and the Creation overhead is large.
2. Only one instance is required to maintain the process and interaction of the entire function.
For example, when a Phone application in Android is started, only one Phone object is created for a Single-card Phone, which is used to manage objects such as RIL, CallTracker, and ServiceStateTracker, the second Phone object does not exist in the mobile Phone to communicate with RILC.
Class Diagram
The class diagram of a singleton is very simple, and it looks very simple. You only need one class to get one instance, But I think Singleton is much more complicated than other creation modes.
If you want to create a Singleton class. Normally, you only need new Singleton (). However, if you want Singleton to have only one instance, you cannot create it using this method, because each time a new instance is created, a new instance is generated:
1. In order not to use new to create a constructor, you must convert the constructor to private;
2. In order to have only one instance, Singleton itself needs to maintain this instance. Therefore, a Singleton instance needs to be defined in the class. Obviously, it should be private because it is an instance of the class, it is not an object instance, so it should also be static;
3. Because it cannot be new, in order to obtain Singleton instances through a method, you have to return the instance through a static method, such as public static Singleton getInstance (), if the instance is null internally, it is created. Otherwise, the instance is returned, <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> Accept + b7dyc/D5rXEt9bO9qOs0tG + rcTcubu0tL2os/bSu7j21 + 688 rWltaXA/accept = "normal hunger ticket mode"> normal hunger ticket Mode
public class Singleton {private static Singleton instance = new Singleton();private Singleton() {// Nothing}public static Singleton getInstance(){return instance;}public void say(){System.out.println("I am singleton");}}
The regular meeting of the hunger ticket is instantiated during class loading. The advantage is that due to the classloder mechanism, when a class is loaded, the loading of this class is mutually exclusive, while the static instance of the Hungry Man Singleton directly creates an instance, the instance can be securely obtained during loading. This avoids thread security issues.
The disadvantage is that the instance will waste resources and time for instantiation during loading. Although it is usually loaded when getInstance is called, there is no way to ensure that other methods will use the instance to create the instance.
Inert loading Singleton Mode
This Singleton class will create an instance when it is loaded. In order to make it create an object only when it is used, set it to null. Let it create a new instance when getInstace is used, that is, inert loading. This is also called a lazy Singleton.
public class lazySingleton {private static lazySingleton instance = null;private lazySingleton() {// TODO Auto-generated constructor stub}public static lazySingleton getInstace() {if (instance==null){instance =new lazySingleton();}return instance;}public void say(){System.out.println("I am lazySingleton");}}
Lock Singleton Mode
The preceding lazy examples won't cause any problems in a single thread, but problems will occur if they are used in a single thread. If both the AB thread use getInstace to obtain the instance of the Singleton, The getInstace method cannot be guaranteed to be executed in one thread until it is executed in another thread, if both threads determine that the instance bit is null, the new instance may be created in the new statement.
To ensure that only one thread can execute getInstance at the same time, you need to lock the method or use the object lock inside the method. However, place the lock in if (instance = null) otherwise, the system may determine true at the same time.
public class SyncSingleton {private static SyncSingleton instance = null;private SyncSingleton() {// TODO Auto-generated constructor stub}public static synchronized SyncSingleton getInstance(){if (instance == null){instance = new SyncSingleton();}return instance;}}
Or
public class SyncSingleton { private static SyncSingleton instance = null; private static final Object classLock = SyncSingleton.class; private SyncSingleton(){} public SyncSingleton getInstance(){ synchronized(classLock){ if(instance == null) instance = new SyncSingleton(); return instance; } } }
Dual Check and lock Singleton
The problem above solves the problem of multithreading, but it also brings about performance problems, because every call to getInstance will be synchronized, but in fact, if the instance has been created, it is good to directly return to the instance. The lock is not needed here. The synchronization lock is required only when a new instance is created, but as mentioned above, when creating a lock, place it outside the if (instance = null) Judgment; otherwise, it may still be true at the same time. Therefore, the following dual-check Singleton mode is available.
Public class extends {private volatile static extends tivesingleton instance = null; private extends tivesingleton () {// TODO Auto-generated constructor stub} public static extends tivesingleton getInstance () {if (instance = null) {// determine whether an instance has been created. If the instance has been created, the system returns the result directly. synchronized (EffectiveSingleton. class) {// if it is not created, it is synchronized and initialized in the synchronization block. Be sure to determine whether the instance has been instantiated if (instance = null) {instance = new EffectiveSingleton () ;}} return instance ;}} again ;}}
In this way, when the initialization of the instance is completed, the getInstance can be returned directly each time, and the synchronization lock is no longer needed.
When getInstance is called for the first time, the Code section of the synchronized block package ensures that the new instance is not called multiple times.
The second if (instance = null) condition is determined to use the first if (instance = null) condition for existing instances, the AB thread may still be determined by the first condition. This requires a condition judgment in the synchronization block.
The dual-check and locking Singleton mode solves the performance problem of the locking Singleton.
Use the singleton mode of static internal classes
A static internal class is also called a nested class. It is more vivid to define it with this name. This means that the relationship between the internal class and the external class is only hierarchical nesting, so when creating the class file, the class file name is in the following format: outer $ inner. java, Which is used exactly the same as two common classes.
On the basis of the ELE. Me ticket, wrap instance = new Singleton () with a static internal class called SingletonHolder.
In this way, even when the Singleton class is loaded, the static internal class SingletonHolder will not be loaded. It will only be loaded when SingletonHolder is used.
At the same time, due to the mutual exclusion of the class loading mechanism, the thread security during instance creation is ensured.
class Singleton { private static class SingletonHolder { private static final Singleton instance = new Singleton(); } private Singleton() { } public static final Singleton getInstance() { return SingletonHolder.instance; }}
Singleton in Android
The example of using PhoneFactory to create a Phone object is as follows:
public class PhoneFactory { static private Phone sProxyPhone = null; ...... public static void makeDefaultPhone(Context context) { synchronized(Phone.class) { if (!sMadeDefaults) { ... sProxyPhone = new PhoneProxy(new GSMPhone(context, sCommandsInterface, sPhoneNotifier)); ... sMadeDefaults = true; } } }
It can be seen that this example conforms to the above locking Singleton mode. Although it is not a dual judgment method to increase efficiency, it is because the makeDefaultPhone of PhoneFactory has basically no multithreading, it is called only when the Phone application is started.
In addition, PhoneFactory uses makeDefaultPhone to create an instance, but uses getdefaphone phone to obtain the instance. In this case, if the instance already exists, the synchronization block is used for determination.