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

Java Design pattern-Singleton pattern

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

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

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.

Introduction

Intent: make sure that a class has only one instance and provide a global access point to it.

The main solution: a class used globally is frequently created and destroyed.

When to use: when you want to control the number of instances and save system resources.

How to solve it: determine whether the system already has this singleton, return if so, and create it if not.

Key code: the constructor is private.

Application example:

There is only one head teacher in a class.

2. Windows is multi-process and multi-threaded. When operating a file, it is inevitable that multiple processes or threads operate a file at the same time, so all files must be processed through a unique instance.

3. Some device managers are often designed for singleton mode. For example, if a computer has two printers, it is necessary to deal with the fact that two printers cannot print the same file when it is output.

Advantages:

1. There is only one instance in memory, which reduces the memory overhead, especially the frequent creation and destruction of instances (such as managing the school home page cache).

2. Avoid multiple occupations of resources (such as writing file operations).

Disadvantages: no interface, can not be inherited, in conflict with the principle of single responsibility, a class should only care about internal logic, not how to instantiate outside.

Use the scene:

1. A unique serial number is required for production.

2. Counters in WEB do not need to be added to the database every time they are refreshed, but are cached first with a single example.

3. The creation of an object consumes too many resources, such as the connection between Icano and the database.

Note: the synchronization lock synchronized (Singleton.class) is required in the getInstance () method to prevent multithreading from entering at the same time, causing the instance to be instantiated multiple times.

Realize

We will create a SingleObject class. The SingleObject class has its private constructor and a static instance of itself.

The SingleObject class provides a static method for the outside world to get its static instance. SingletonPatternDemo, our demo class uses the SingleObject class to get the SingleObject object.

Step 1

Create a Singleton class.

Public class SingleObject {/ / create an object of SingleObject private static SingleObject instance = new SingleObject (); / / make the constructor private so that the class will not be instantiated private SingleObject () {} / / to get the only available object public static SingleObject getInstance () {return instance;} public void showMessage () {System.out.println ("Hello World!");} step 2

Get a unique object from the singleton class.

Public class SingletonPatternDemo {public static void main (String [] args) {/ / illegal constructor / / compile-time error: constructor SingleObject () is invisible / / SingleObject object = new SingleObject (); / / get the only available object SingleObject object = SingleObject.getInstance (); / / display message object.showMessage ();} step 3

Execute the program and output the result:

Hello World! Several ways to realize the singleton pattern

The singleton pattern can be implemented in several ways, as follows:

1. Lazy, thread unsafe

Whether Lazy is initialized: yes

Whether multithreading is safe: no

Difficulty to achieve: easy

Description: this is the most basic implementation, and the biggest problem with this implementation is that it does not support multithreading. Because synchronized is not locked, it is not strictly a singleton pattern.

In this way, lazy loading is obvious, does not require thread safety, and does not work properly in multithreading.

Example

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

The next few implementations all support multithreading, but differ in performance.

2. Lazy, thread safe

Whether Lazy is initialized: yes

Whether multithreading is safe: yes

Difficulty to achieve: easy

Description: this approach has a good lazy loading and works well in multithreading, but it is inefficient and does not require synchronization in 99% of the cases.

Advantages: initialize only the first call to avoid memory waste.

Disadvantages: synchronized must be locked to guarantee singletons, but locking will affect efficiency.

The performance of getInstance () is not critical to the application (this method is used infrequently).

Example

Public class Singleton {private static Singleton instance; private Singleton () {} public static synchronized Singleton getInstance () {if (instance = = null) {instance = new Singleton ();} return instance;}} 3

Whether Lazy is initialized: no

Whether multithreading is safe: yes

Difficulty to achieve: easy

Description: this method is more commonly used, but it is easy to produce junk objects.

Advantages: without locking, the execution efficiency will be improved.

Disadvantages: initialize the class when it is loaded, wasting memory.

It avoids the problem of multi-thread synchronization based on the classloader mechanism, but instance is instantiated when the class is loaded. Although there are many reasons for class loading, most of them call the getInstance method in the singleton mode, but it is not sure that there are other ways (or other static methods) that lead to class loading. At this time, initializing instance obviously does not achieve the effect of lazy loading.

Example

Public class Singleton {private static Singleton instance = new Singleton (); private Singleton () {} public static Singleton getInstance () {return instance;}} 4, double check lock / double check lock (double-checked locking)

JDK version: starting from JDK1.5

Whether Lazy is initialized: yes

Whether multithreading is safe: yes

Difficulty in implementation: more complex

Description: this approach uses a double lock mechanism, which is safe and can maintain high performance in the case of multithreading.

The performance of getInstance () is critical to the application.

Example

Public class Singleton {private volatile static Singleton singleton; private Singleton () {} public static Singleton getSingleton () {if (singleton = = null) {synchronized (Singleton.class) {if (singleton = = null) {singleton = new Singleton ();} return singleton;}} 5, registered / static inner class

Whether Lazy is initialized: yes

Whether multithreading is safe: yes

Difficulty of implementation: general

Description: this method can achieve the same effect of double check lock, but it is easier to implement. Use delayed initialization for static domains, which should be used instead of double locking. This method is only applicable to static domains, and double locking can be used when the instance domain needs to be deferred for initialization.

This method also uses the classloader mechanism to ensure that there is only one thread when initializing the instance, which is different from the third method: in the third method, as long as the Singleton class is loaded, then the instance will be instantiated (not achieving the lazy loading effect), while in this way, the Singleton class is loaded and the instance is not necessarily initialized. Because the SingletonHolder class is not actively used, the SingletonHolder class is only explicitly loaded by explicitly calling the getInstance method, thus instantiating the instance. Imagine that if instantiating instance is resource-consuming and you want it to delay loading, on the other hand, you don't want to instantiate when the Singleton class loads, because there is no guarantee that the Singleton class may be actively used and loaded elsewhere, then instantiating instance at this time is obviously not appropriate. At this point, this approach is more reasonable than the third way.

Example

Public class Singleton {private static class SingletonHolder {private static final Singleton INSTANCE = new Singleton ();} private Singleton () {} public static final Singleton getInstance () {return SingletonHolder.INSTANCE;}} 6, enumeration

JDK version: starting from JDK1.5

Whether Lazy is initialized: no

Whether multithreading is safe: yes

Difficulty to achieve: easy

Description: this implementation has not been widely adopted, but it is the best way to implement the singleton pattern. It is more concise, automatically supports serialization mechanisms, and absolutely prevents multiple instantiations.

This approach is advocated by Effective Java author Josh Bloch, which not only avoids the problem of multithreaded synchronization, but also automatically supports serialization mechanisms to prevent deserialization from recreating new objects and absolutely prevent multiple instantiations. However, because the enum feature was added after JDK1.5, writing in this way is unfamiliar and rarely used in practice.

Private constructors cannot be called through reflection attack.

Example

Public enum Singleton {INSTANCE; public void whateverMethod () {}}

Rule of thumb: in general, the first and second lazy methods are not recommended, and the third hungry way is recommended. The fifth registration method is used only if you want to explicitly achieve the lazy loading effect. If deserialization is involved in creating objects, you can try using the sixth enumeration method. If you have other special needs, you can consider using the fourth double lock method.

The original text is from: https://www.linuxprobe.com/pattern-singleton-pattern.html

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

Servers

Wechat

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

12
Report