People often ask me how to advance in Android learning? No matter how you go, design patterns are essential for advancement. Understanding and applying design patterns will be of great help to your subsequent code writing and architecture design. So starting today, I will take some time to share with you the design pattern series.
What is a design pattern? In fact, a simple understanding is that it is just a summary of some experiences left by our predecessors, and then these experiences are named Design Pattern, which means design pattern. By using design patterns, we can make our code more reusable, more maintainable, and make your code more elegant. In theory, there are 23 design patterns, but I will only share some commonly used design patterns on the Android platform. Today, I will share the most commonly used singleton pattern.
The hungry approach is the simplest implementation method. This approach is suitable for situations where a singleton is required during initialization. This approach is simple and crude. If the singleton object is initialized very quickly and occupies very little memory, this approach is more appropriate. It can be directly loaded and initialized 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 certain scenario and is not used under normal circumstances, the hungry singleton mode is not appropriate. At this time, the lazy approach is needed to delay the loading of the singleton on demand. Lazy
The biggest difference between the lazy approach and the hungry approach is that the initialization of the singleton is delayed until it is needed, which is very useful in some situations. For example, if a singleton is not used very often, but the functions it provides are very complex, and loading and initializing it consumes a lot of resources, then the lazy approach is a very good choice. Some basic application methods of the singleton pattern are introduced above, but the usage methods mentioned above all have an implicit premise, that is, they are all applied under single-threaded conditions. Once they are switched to multi-threaded conditions, there is a risk of errors. If there are multiple threads, the hungry approach will not cause any problems, because the JVM will only load the singleton class once, but the lazy approach may cause the problem of creating the singleton object repeatedly. Why is there such a problem? Because the lazy approach is thread-unsafe when creating a singleton, multiple threads may call its newInstance method concurrently, resulting in multiple threads creating multiple copies of the same singleton. Is there any way to make the lazy single-interest model thread-safe? The answer is definitely yes, that is, to use a synchronous lock to achieve it.
This is the most common way to solve synchronization problems. Use synchronized lock (Singleton.class) to prevent multiple threads from entering at the same time and causing the instance to be instantiated multiple times. Here is an example of using this method in Android:
The above is the singleton usage related to the input method class in the Android source code. But there is actually a better way:
You can see that another layer of if is added outside synchronized (Singleton.class) above. This is to avoid executing synchronized (Singleton.class) to obtain the object lock the next time the instance is instantiated, thereby improving performance. The above two methods are still quite troublesome. We can't help but ask, is there a better way to achieve it? The answer is yes. We can use the JVM's class loading mechanism to achieve it. In many cases, JVM has provided us with synchronization control, such as: Data initialized in the static{} block When accessing final fields etc. Because the JVM will ensure that the data is synchronized when loading the class, we can implement it like this: Use inner classes to create object instances in the inner classes. In this way, as long as the inner class is not used in the application, the JVM will not load the singleton class, and will not create a singleton object, thus achieving lazy delayed loading and thread safety. The implementation code is as follows:
The singleton class implemented in this way is thread-safe and very simple to use. Mom no longer has to worry that my singleton is not a singleton. However, this is not the simplest way. Effective Java recommends a simpler and more convenient way to use it, which is to use enumeration.
Here’s how to use it:
By default, the creation of enumeration instances is thread-safe. (Creating a singleton of an enumeration class is also thread-safe at the JVM level), so there is no need to worry about thread safety issues. In theory, enumeration classes are the easiest way to implement singleton mode. Generally, the singleton pattern includes five ways of writing, namely hungry, lazy, double-checked lock, static inner class and enumeration. I believe that after reading this, you have a full understanding of the singleton pattern. Choose the singleton pattern you like best according to different scenarios! |
<<: Writing command line programs in Swift
>>: Android-Super simple to achieve picture rounded corners
During the epidemic, home life cannot be separate...
Assuming that all other conditions remain unchang...
Website construction is developing rapidly now, a...
During the Spring Festival, everyone must have fo...
A few days ago, a piece of news became a hot sear...
You probably know there are eight models for data...
When we do website optimization, it is essential ...
Since 2016, when information flow entered the cou...
When Dangdang held the “50 off for purchases over...
The resurgence of the epidemic in March caught pe...
[Tong Yao was surrounded by men at the elevator e...
Creative team: China Science and Technology Museu...
When it comes to data analysis , people often thi...
One minute with the doctor, the postures are cons...
As spring comes and flowers bloom, marketing in v...