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 in Java

2025-04-11 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

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

How to implement Singleton in Java? in view of this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible method.

1. The public static member is a final domain / / Singleton with public final field

Public class Elvis {

Public static final Elvis INSTANCE = new Elvis ()

Pritvate Elvis () {...}

Public void leaveTheBuilding () {...}

}

In this class, we only have a private constructor that is called only once when the finaldomain is initialized. Due to the lack of constructors that can be used, subsequent programs can no longer create Elvis objects. This ensures that there is one and only one Elvis object throughout the life cycle of the Java program.

It is important to note, however, that some highly privileged clients can invoke private constructors through the reflection mechanism with the help of AccessibleObject.setAccessible methods. To avoid such a possible attack, you can modify the constructor to throw an exception when asked to create a second instance.

The main advantage of the public domain approach is that API makes it clear that the class is a Singleton, which is, after all, a public static property. In addition, this method is simpler.

2. The public static member is a static factory method / / Singleton with static factory

Public class Elvis {

Private static final Elvis INSTANCE = new Elvis ()

Pritvate Elvis () {...}

Public static Elvis getInstance () {return INSTANCE;}

Public void leaveTheBuilding () {...}

}

Obviously, no matter how you call the getInstance method, you return a reference to the same object. Note that the reflex attack problem suggested above still exists.

The static factory approach has three advantages

First, it provides more flexibility, and we are free to adjust whether the class is Singleton without changing the API. The factory method returns a unique instance of the class, but it can easily be modified to something else, such as providing a unique instance for each thread that calls the method.

Second, we can write a generic Singleton factory if the program requires it.

Third, we can use method references as providers. For example, Elvis::instance is a Supplier.

< Elvis >

(note: method reference is a new feature of Java8)

Unless we need one of the above advantages, we should choose a more easy-to-understand way to use the public domain.

3. Make the Singleton class implemented using the above method serializable

For Singleton implemented using the above two methods, you can't just add implements Serializable to the declaration to make them serializable. To maintain and guarantee Singleton, we must live that all instance domains are instantaneous and provide a readResolve method. Otherwise, a new instance will be created each time we serialize. To prevent this, we will add a readResolve method like this to the Elvis class.

/ / readResolve method to preserve singleton property

Private Object readResolve () {

/ / Return the one true Elvis and let the garbage collector take care of the Elvis impersonator

Return INSTANCE

}

3. Singleton implementation-declares an enumerated type containing a single element / / Enum singleton-the preferred approach

Public enum Elvis {

INSTANCE

Public void leaveTheBuilding () {...}

}

This approach is functionally similar to the public domain approach, but provides a more concise serialization mechanism for free, absolutely preventing multiple instantiations, even in the face of complex serialization or reflection attacks. Although this approach is not widely used, enumerated types of single elements are often the best way to implement Singleton. Note that this method is not appropriate if Singleton must extend a superclass instead of Enum (although enumerations can be declared to implement the interface).

This is the answer to the question about how to implement Singleton in Java. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel for more related knowledge.

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