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 realize singleton design pattern

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly explains "how to realize singleton design pattern". The content of the explanation in this article is simple and clear, and it is easy to learn and understand. let's study and learn "how to realize singleton design pattern".

Singleton mode

Singleton pattern (Singleton Pattern) is one of the simplest design patterns in Java. This type of design pattern is a creative pattern, which provides the best way to create objects.

This pattern involves a single class that is responsible for creating its own objects while ensuring that only a single object is created. This class provides a way to access its unique object directly without instantiating the object of the class.

To put it simply:

A singleton class can have only one instance.

The singleton class must create its own unique instance.

The singleton class must provide this instance to all other objects.

The singleton pattern looks very simple and easy to implement. The singleton model is a high-frequency interview question in the interview. I hope you can study seriously, master the singleton model, enhance the core competitiveness, give extra points to the interview, and get the Offer smoothly.

1. Singleton pattern definition

Definition of Singleton pattern: a pattern in which a class has only one instance and the class can create that instance on its own, and provides a global access point to it.

two。 Singleton mode function

The singleton pattern is mainly used to solve the problem, and a class used globally is frequently created and destroyed.

Core idea: when creating an object, first determine whether the object already exists, if so, return, if not, create it.

The key code is to privatize the constructor; only one object is created globally.

3. Singleton mode application scenario

For Java, the singleton pattern ensures that there is only a single instance in a JVM. The application scenarios of singleton mode mainly include the following aspects.

For some classes that need to be created frequently, using singletons can reduce the memory pressure of the system and reduce GC.

When only one object is required to be generated, such as the monitor in a class, the ID number of each person, and so on.

Some classes take a lot of resources to create instances, or instantiation takes a long time and is often used.

Some class needs to be instantiated frequently, and the created objects are frequently destroyed, such as multithreaded thread pool, network connection pool, and so on.

Objects that frequently access a database or file.

For some operations that control the hardware level, or should be a single control logic operation on the system, if there are multiple instances, the system will be completely out of order.

When objects need to be shared. Because singleton mode allows only one object to be created, sharing the object can save memory and speed up object access. Such as configuration objects in Web, connection pooling of databases, etc.

3. Singleton pattern structure

The main roles of the singleton pattern are as follows.

Singleton class: a class that contains an instance and can create the instance itself.

Access classes: classes that use singletons.

Singleton pattern class diagram

4. Singleton pattern implementation

The singleton pattern is usually implemented in two forms.

4.1 lazy style

The characteristic of this pattern is that no singleton is generated when the class is loaded, which is created only when the getlnstance method is called for the first time. The code is as follows:

Public class LazySingleton {/ / guarantee instance synchronization in all threads private static volatile LazySingleton instance = null; / / private avoid classes being instantiated externally private LazySingleton () {} / / get singleton object public static synchronized LazySingleton getInstance () {/ / getInstance method preceded by synchronization if (instance = = null) {instance = new LazySingleton () } return instance;}}

If you are writing a multithreaded program, do not delete the keywords volatile and synchronized in the above code, otherwise there will be thread unsafe issues. Thread safety can be ensured without deleting these two keywords, but synchronizing each access will affect performance and consume more resources, which is the disadvantage of lazy singletons.

A single case of hungry Han style

The characteristic of this pattern is that once the class is loaded, a singleton is created, ensuring that the singleton already exists before the getInstance method is called.

Public class HungrySingleton {private static final HungrySingleton instance = new HungrySingleton (); private HungrySingleton () {} public static HungrySingleton getInstance () {return instance;}}

The hungry Han singleton has created a static object for the system to use at the same time as the class is created, and it will not be changed in the future, so it is thread-safe and can be directly used for multithreading without problems.

Other

In addition to what has been mentioned above, there are also singletons implemented by double check locks / double check locks (double-checked locking), registered / static inner classes, enumerations, and so on.

Summary

Advantages of the singleton model:

Singleton mode ensures that there is only one instance in memory, reducing memory overhead.

Multiple occupancy of resources can be avoided.

Singleton mode sets global access points to optimize and share access to resources.

Disadvantages of singleton mode:

The singleton mode generally has no interface and is difficult to expand. If you want to expand, there is no second way to violate the principle of opening and closing except to modify the original code.

In concurrent testing, singleton mode is not conducive to code debugging. During debugging, you cannot simulate the generation of a new object if the code in the singleton is not finished.

The functional code of the singleton pattern is usually written in a class, and if the functional design is unreasonable, it is easy to violate the principle of single responsibility.

Thank you for your reading. the above is the content of "how to realize singleton design pattern". After the study of this article, I believe you have a deeper understanding of how to realize singleton design pattern. the specific use of the situation also needs to be verified by practice. 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