乐闻世界logo
搜索文章和话题

What is the Singleton Pattern in Java?

2月7日 12:38

The Singleton pattern is a design pattern used to ensure that only one instance of a class exists and provides a global access point to that instance. In Java, the Singleton pattern is typically implemented by making the constructor private, defining a private static variable to hold the single instance, and providing a public static method to access the instance. This ensures that regardless of where in the code the method is called, it always returns the same object instance. For example, the following is a Java class implementing the Singleton pattern:

java
public class Singleton { private static Singleton instance; private Singleton() {} // private constructor prevents external instantiation public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); // creates the instance only when not yet created } return instance; } }

This implementation is known as lazy initialization, as it creates the instance only when it is first needed. Another approach is called eager initialization, which creates the instance immediately when the class is loaded:

java
public class Singleton { private static Singleton instance = new Singleton(); private Singleton() {} public static Singleton getInstance() { return instance; } }

Both approaches have their pros and cons. Lazy initialization is lazy-loading, which saves resources, but may require additional synchronization in a multithreaded environment. Eager initialization is thread-safe but creates the instance regardless of whether it is used, potentially wasting resources.

标签:Java