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 understand the singleton pattern of Java design pattern

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

Share

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

This article mainly explains "how to understand the singleton pattern of Java design pattern". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to understand the singleton pattern of Java design pattern".

I. what is the singleton model

Singleton pattern is a commonly used software design pattern, which defines that the class of singleton object can only allow one instance to exist.

In many cases, the whole system only needs to have a global object, which helps us to coordinate the behavior of the system as a whole. For example, in a server program, the configuration information of the server is stored in a file, and the configuration data is read uniformly by a singleton object, and then other objects in the service process obtain the configuration information through the singleton object. This approach simplifies configuration management in complex environments.

The singleton is mainly implemented through the following two steps:

1. Define the constructor of the class as a private method, so that code elsewhere cannot instantiate the object of the class by calling the constructor of the class, but only through the static method provided by the class.

two。 Provide a static method within the class, and when we call this method, return the reference if the reference held by the class is not null, create an instance of the class if the reference held by the class is empty, and assign the reference of the instance to the reference maintained by the class.

Second, the application scenario of the singleton model

To take a small example, on our windows desktop, we open a Recycle Bin, and when we try to open a new Recycle Bin again, the Windows system will not pop up a new Recycle Bin window for you. That is to say, during the whole system operation, the system maintains only one instance of the recycle bin This is a typical singleton pattern.

Continuing to talk about the Recycle Bin, there is no need to open two Recycle Bin windows at the same time in practice. If I need to consume a lot of resources every time I create the Recycle Bin, and the resources are shared between each Recycle Bin, then multiple instances are created without the need to create the instance many times. This will put an unnecessary burden on the system and result in a waste of resources.

To take another example, the counter of a website is generally implemented in singleton mode. If you have multiple counters, each user's access refreshes the value of the counter, so that the value of your real count is difficult to synchronize. However, if the singleton pattern is used, there will be no such problem, and thread safety problems can be avoided. Similarly, multi-threaded thread pools are generally designed in singleton mode, because the thread pool needs to facilitate the control of threads in the pool.

Similarly, the singleton mode is suitable for logging applications of some applications, or reading configuration files in web development. For example, HttpApplication is a typical singleton application.

From the above examples, we can summarize the scenarios and pros and cons that are suitable for using singleton mode:

Applicable scenarios:

1. Environments that need to generate unique sequences

two。 Objects that need to be frequently instantiated and then destroyed.

3. Objects that take too much time or resources to create, but are often used.

4. A convenient environment for resources to communicate with each other

Third, the advantages and disadvantages of the singleton model

Advantages:

There is only one object in memory, saving memory space

Avoiding frequent creation and destruction of objects can improve performance

Avoid multiple occupations of shared resources and simplify access

Provide a global access point for the entire system.

Disadvantages:

Not suitable for objects that change frequently

Abuse of singletons will bring some negative problems, such as designing database connection pool objects as singleton classes to save resources, which may lead to connection pool overflow due to too many programs sharing connection pool objects.

If the instantiated object is not used for a long time, the system will think that the object is garbage and be reclaimed, which may result in the loss of object state.

Fourth, the realization of singleton mode 1. Hungry / / hungry Chinese singleton public class Singleton1 {/ / points to a private static reference to its own instance, actively creates private static Singleton1 singleton1 = new Singleton1 (); / / Private constructor private Singleton1 () {} / / static public method with its own instance as the return value, static factory method public static Singleton1 getSingleton1 () {return singleton1;}}

We know that classes are loaded on demand and once. Therefore, when the above singleton class is loaded, an object is instantiated and given to its own reference for use by the system, and since the class is only loaded once in its lifetime, only one instance is created, that is, the singleton is fully guaranteed.

Pros: this method is relatively simple, that is, it is instantiated when the class is loaded. The problem of thread synchronization is avoided.

Disadvantages: the instantiation is completed when the class is loaded, which does not achieve the effect of Lazy Loading. If this instance has never been used from beginning to end, it will result in a waste of memory.

two。 Lazy / / lazy singleton public class Singleton2 {/ / points to the private static reference private static Singleton2 singleton2 of your own instance / / Private constructor private Singleton2 () {} / / static public method with its own instance as return value, static factory method public static Singleton2 getSingleton2 () {/ / passively create if (singleton2 = = null) {singleton2 = new Singleton2 ();} return singleton2;}}

We can see from the lazy singleton that the singleton instance is loaded late, that is, an object is instantiated and given to its own reference only when it is actually used.

This type of writing works like Lazy Loading, but can only be used in a single thread. If, in multithreading, one thread enters the if (singleton = = null) judgment block and the other thread passes the judgment statement before it can be executed, multiple instances will be generated. Therefore, this approach cannot be used in a multithreaded environment.

3. Double locking mechanism public class Singleton {private static Singleton instance; / / create a static read-only process helper object private static readonly object syncRoot = new object () when the program is running Private Singleton () {} public static Singleton GetInstance () {/ / determine whether it exists first There is no further lock processing if (instance = = null) {/ / only one thread of the program that is locked at the same time can enter lock (syncRoot) {if (instance = = null) {instance = new Singleton () } return instance;}}

The Double-Check concept is not unfamiliar to multithreaded developers. As shown in the code, we did two if (singleton = = null) checks to ensure thread safety. In this way, the instantiated code only needs to be executed once, and when it is accessed again later, the if is judged (singleton = = null) and the instantiated object is directly return.

Using double detection synchronous delayed loading to create a singleton is a very excellent practice, which not only ensures the singleton, but also improves the running efficiency of the program.

Advantages: thread safety; delayed loading; high efficiency.

4. Static initialization / / prevents derivation from happening, while derivation may add instance public sealed class Singleton {/ / create an instance the first time any member of the class is referenced, and the common language runtime handles the variable initialization private static readonly Singleton instance=new Singleton (); private Singleton () {} public static Singleton GetInstance () {return instance;}}

In practical applications, C# and the common language runtime also provide a "static initialization" method, which does not require developers to explicitly write thread-safe code to solve the problem that it is unsafe in a multithreaded environment.

Thank you for your reading, the above is the content of "how to understand the singleton pattern of Java design pattern". After the study of this article, I believe you have a deeper understanding of how to understand the singleton pattern of Java design pattern. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

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