Junior
How to create a singleton instance of a class in Android?
sobes.tech AI
Answer from AI
To create a single instance of a class in Android, the Singleton pattern is usually used.
There are several ways to implement Singleton:
-
Lazy initialization with synchronization:
public class Singleton { private static Singleton instance; private Singleton() { // Private constructor prevents creating other instances } public static synchronized Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }- Pros: Thread-safe.
- Cons: Synchronization can reduce performance when called frequently.
-
Initialization at class load (Eager initialization):
public class Singleton { private static final Singleton instance = new Singleton(); private Singleton() {} public static Singleton getInstance() { return instance; } }- Pros: Thread-safe without explicit synchronization. Simpler.
- Cons: Instance is created immediately when the class loads, even if not used.
-
Double-checked locking:
public class Singleton { private static volatile Singleton instance; private Singleton() {} public static Singleton getInstance() { if (instance == null) { synchronized (Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; } }- Pros: Increased performance compared to simple synchronization, initialization only when needed.
- Cons: Requires
volatilefor correct operation in multithreaded environment (since Java 5). More complex.
-
Static inner class:
public class Singleton { private Singleton() {} private static class SingletonHolder { public static final Singleton INSTANCE = new Singleton(); } public static Singleton getInstance() { return SingletonHolder.INSTANCE; } }- Pros: Thread-safe, lazy initialization, easy to implement. The most recommended approach in modern Java versions.
-
Using Enums:
public enum Singleton { INSTANCE; // Add class methods public void doSomething() { // ... } }- Pros: The simplest and thread-safe way, resistant to serialization and reflection. Often considered best practice.
The choice of implementation depends on specific performance and complexity requirements. In Android, Enum or static inner class are often used.