Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to analyze the design pattern of singleton in Android Java language

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article shows you how to parse the singleton design pattern in the Android Java language. The content is concise and easy to understand, which will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.

Concept

Singleton pattern, also known as singleton pattern or singleton pattern, means that a class has only one instance and provides a global access point.

Realization idea

Set a private static variable sInstance,sInstance type as the current class in the singleton class to hold the instance of the singleton.

Set the (no parameter) constructor to private to avoid using new to construct multiple instances externally.

Provide a static method of public, such as getInstance, to return the * instance sInstance of this class.

The instance of the above singleton can be created in the following ways, and each implementation needs to ensure the * * nature of the instance.

Hungry Han style

The hungry Chinese style refers to the creation of a singleton instance when the class is loaded. If the constructor of the singleton class does not contain too much operation processing, the hungry Han style is actually acceptable.

The common code for hungry Chinese is as follows, which is executed when the SingleInstance class is loaded.

Private static SingleInstance sInstance = new SingleInstance ()

Initialize the instance of *, and then getInstance () can return sInstance directly.

Public class SingleInstance {private static SingleInstance sInstance = new SingleInstance (); private SingleInstance () {} public static SingleInstance getInstance () {return sInstance;}}

The problem of hungry Han style

If there is too much processing in the constructor, it will result in slow loading of this class, which can cause performance problems.

If the hungry Chinese style is used, only the class is loaded, and there is no actual call, which will result in a waste of resources.

Lazy style

Lazy refers to the creation of a singleton instance when it is used for * * times. In this case, the problems that may be encountered in the above hungry Han style are avoided.

But considering the concurrency of multithreading, we can't simply implement it like the following code.

Public class SingleInstance {private static SingleInstance sInstance; private SingleInstance () {} public static SingleInstance getInstance () {if (null = = sInstance) {sInstance = new SingleInstance ();} return sInstance;}}

The above code has the possibility of creating multiple instances when multiple thread-intensive calls to getInstance are made. For example, thread An enters the code block null = = sInstance, and when thread A does not create a completed instance, if thread B also enters the code block, it will inevitably result in two instances.

Synchronized modification method

Using synchrnozed to modify the getInstance method is probably the easiest way to guarantee singleton security with multithreading.

After the synchronized-decorated method, when a thread enters to call the method, the thread enters the method only after another thread leaves the current method. So you can guarantee that only one thread enters the getInstance at any one time.

Public class SingleInstance {private static SingleInstance sInstance; private SingleInstance () {} public static synchronized SingleInstance getInstance () {if (null = = sInstance) {sInstance = new SingleInstance ();} return sInstance;}}

However, using synchronized to modify the getInstance method will inevitably lead to performance degradation, and getInstance is a method that is called frequently. Although this method can solve the problem, it is not recommended.

Double check lock

Use double check to lock, first enter the method and check null = = sInstance. If the check passes *, that is, no instance is created, enter the synchronization block controlled by synchronized, and check whether the instance is created again. If it has not been created yet, the instance is created.

Double check locking ensures that only one instance is created under multithreading, and the locked code block is synchronized only before the instance is created. If you enter the method after the instance has been created, the code for the synchronization block will not be executed.

Public class SingleInstance {private static volatile SingleInstance sInstance; private SingleInstance () {} public static SingleInstance getInstance () {if (null = = sInstance) {synchronized (SingleInstance.class) {if (null = = sInstance) {sInstance = new SingleInstance ();} return sInstance;}}

What is volatile?

Volatile is a lightweight synchronized that ensures the "visibility" of shared variables in multiprocessor development. Visibility means that when one thread modifies a shared variable, another thread can read the modified value. After you decorate the sInstance variable with volatile, you can ensure that the sInstance variable is handled correctly among multiple threads.

For more information about volatile, visit the in-depth analysis of how Volatile is implemented.

Using static mechanism

In Java, the static initialization of the class will be triggered when the class is loaded, we can use this principle, we can make use of this feature, combined with the inner class, we can implement the following code to create an instance like a lazy guy.

Public class SingleInstance {private SingleInstance () {} public static SingleInstance getInstance () {return SingleInstanceHolder.sInstance;} private static class SingleInstanceHolder {private static SingleInstance sInstance = new SingleInstance ();}}

With regard to this mechanism, you can learn more about double-checked locking and delayed initialization.

Curious question

Is it true that there is only one object?

In fact, the singleton model can not guarantee the sex of the instance, as long as we find a way, we can still break this sex. The following methods can be implemented.

With reflection, although the constructor is private, it doesn't work in front of reflection.

If the singleton class implements cloneable, multiple instances can still be copied.

Object serialization in Java can also result in the creation of multiple instances. Avoid using the readObject method.

Using multiple class loaders to load singleton classes can also lead to the problem of creating multiple instances side by side.

Can a single case be inherited?

Whether a singleton class can be inherited depends on the circumstances.

Circumstances that can be inherited

Inheritance is possible when the subclass is the inner class of the parent singleton class.

Public class BaseSingleton {private static volatile BaseSingleton sInstance; private BaseSingleton () {} public static BaseSingleton getInstance () {if (null = = sInstance) {synchronized (BaseSingleton.class) {if (null = = sInstance) {sInstance = new BaseSingleton ();} return sInstance } public static class MySingleton extends BaseSingleton {}}

But the above is only allowed in compilation and execution, but inheriting a singleton has no practical meaning, but it will get twice the result with twice the effort, and the cost is greater than writing a new singleton class. If you are interested in children's shoes, you can try to toss about.

A situation in which one cannot inherit.

If the subclass is a separate class, not the inner class of the singleton class, then there will be an error Implicit super constructor BaseSingleton () is not visible for default constructor. Must define an explicit constructor, the main reason is that the constructor of the singleton class is private, the solution is to make the constructor visible, but this does not guarantee the singleton. Therefore, this way can not be inherited.

In general, singleton classes do not inherit.

Singleton vs static variable

Global static variables can also achieve the effect of a singleton, but using global variables does not guarantee the creation of only one instance, and using the form of global variables requires team constraints, which may cause problems in execution.

About GC

Because another static variable in the singleton class holds the singleton instance, the singleton object is less likely to be recycled by GC than the ordinary object. The collection of singleton objects should occur after their class loaders are recycled by GC, which is generally not easy to occur.

The above content is how to analyze the singleton design pattern in Android Java language. have you learned the knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report