Singleton Pattern of Android Design Patterns

Original address: Please scan the WeChat public account of stormzhang after the article - AndroidDeveloper


The previous article " How to advance Android development? " mentioned that design patterns are necessary for advanced development. The understanding and application of design patterns will help you a lot in code writing and architecture design, so start today. I will take the time to share the design pattern series with you from time to time.


What are design patterns? In fact, a simple understanding is just a summary of some experiences left by predecessors, and then these experiences are named Design Pattern, which translates to the meaning of design patterns. By using design patterns, we can make our code more reusable. The maintainability is higher, and your code is written more elegantly. There are 23 design patterns in theory, but I will only share some design patterns commonly used on the Android platform. Today, I will share the most commonly used singleton pattern first.


Hungry Chinese




"Hungry Chinese style" is the simplest implementation method. This implementation method is suitable for those situations where a singleton is used during initialization. This method is simple and rude. If the singleton object is initialized very quickly and occupies very little memory When this method is more appropriate, it can be loaded and initialized directly when the application starts.


However, if the singleton initialization operation takes a long time and the application has requirements for startup speed, or the singleton occupies a large amount of memory, or the singleton is only used in a specific scenario, and generally In this case, when it is not used, it is not appropriate to use the "hungry-style" singleton mode. In this case, a "lazy-style" method is needed to delay loading singletons on demand.


lazy




The biggest difference between "lazy man style" and "hungry man style" is that the initialization operation of singleton is delayed until needed, which is very useful in some occasions. For example, a singleton is not used many times, but the functions provided by this singleton are very complex, and loading and initialization consumes a lot of resources. At this time, using "lazy man" is a very good choice.


Singleton pattern under multithreading

The above introduces some basic application methods of the singleton pattern, but the usage methods mentioned above all have an implicit premise, that is, they are all applied under the condition of single thread, and once they are replaced by multithreading, there will be errors. risks of.


In the case of multi-threading, the "hungry style" will not have a problem, because the JVM will only load the singleton class once, but the "lazy style" may have the problem of repeatedly creating singleton objects. Why is there such a problem? Because the "lazy guy" is thread-unsafe when creating a singleton, multiple threads may call his newInstance method concurrently, causing multiple threads to create multiple copies of the same singleton.


So is there a way to make the "lazy man-style" simple interest mode also thread-safe? The answer is definitely yes, that is to achieve it by adding synchronization locks.


lazy synchronization lock




This is the most common way to solve synchronization problems, using synchronization lock synchronized (Singleton.class) to prevent multiple threads from entering at the same time and causing instance to be instantiated multiple times. Here is an example of using this method on Android:


InputMethodManager example




The above is the singleton usage related to the input method class in the Android source code.


But there is actually a better way as follows:


double check lock




It can be seen that a layer of if is added to the synchronized (Singleton.class) above, which is to improve the performance without executing the synchronized (Singleton.class) to obtain the object lock next time after the instance has been instantiated.


The above two methods are still quite troublesome, we can't help but ask, is there a better way to implement it? The answer is yes. We can use the JVM's class loading mechanism to achieve this. In many cases the JVM already provides us with synchronization control, such as:


  • Data initialized in static{} blocks

  • When accessing final fields

  • etc


Because the JVM will ensure that the data is synchronized when the class is loaded, we can achieve this:


Use inner classes to create object instances in this inner class. In this way, as long as the inner class is not used in the application, the JVM will not load the singleton class, and the singleton object will not be created, thus achieving "lazy" lazy loading and thread safety.


The implementation code is as follows:


static inner class




The singleton class implemented in this way is thread-safe, and it is very simple to use. Mama no longer has to worry that my singleton is not a singleton.


However, this is not the easiest way. A more concise and convenient way to use is recommended in "Effective Java", which is to use enumeration.


Enumeration type singleton pattern





The method of use is as follows:




Summarize

The general singleton pattern includes 5 ways of writing, namely hungry, lazy, double check lock, static inner class and enumeration. I believe that after reading it, you have a full understanding of the singleton pattern. Choose the singleton pattern you like the most according to different scenarios!


grateful

This article refers to a colleague's article, and supplements and summarizes it here, thank you.

Link: http://tedyin.me/2016/03/13/singlton-pattern/


WeChat does not support external links. You can click "Read the original text" to view it. If you think it is helpful, you may wish to forward it and support it. Press and hold the QR code to subscribe.


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324155515&siteId=291194637