Home >Java >javaTutorial >Detailed explanation of singleton pattern in Java design patterns
The singleton pattern in Java is implemented through the following steps: Create a private class constructor. Create a private static variable as a reference to the unique instance. Provide a public static method to obtain the instance. Declare static reference variables as final. Declare the implementation class as final.
Java Design Patterns: Singleton Pattern
Introduction
Singleton Pattern Is a way to ensure that there can only be one instance of a class in an application. It helps maintain state consistency, avoids unnecessary object creation, and simplifies management.
Implementation of the singleton pattern in Java
In Java, the singleton pattern can be implemented using the following steps:
Sample code:
public class Singleton { private static final Singleton INSTANCE = new Singleton(); private Singleton() { // 私有构造函数 } public static Singleton getInstance() { return INSTANCE; } }
Practical case
Consider a messaging application that manages user sessions. The application needs to maintain a unique reference to the current user in order to track their activities and preferences throughout the session. The singleton pattern can be used to maintain this unique user instance, as shown below:
public class UserManager { private static final UserManager INSTANCE = new UserManager(); private User currentUser; private UserManager() { // 私有构造函数 } public static UserManager getInstance() { return INSTANCE; } public void setCurrentUser(User user) { this.currentUser = user; } public User getCurrentUser() { return currentUser; } }
By using the singleton pattern, the UserManager
class can ensure that only one copy of the user session state is maintained and managed. This helps simplify user management and ensures consistency across applications.
The above is the detailed content of Detailed explanation of singleton pattern in Java design patterns. For more information, please follow other related articles on the PHP Chinese website!