What is: Singleton is a design pattern that restricts the instantiation of a class to one object. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects.
When to use: This is useful when exactly one object is needed to coordinate actions across the system.
How to use in JAVA:
public class SingletonDemo { private static SingletonDemo instance = null; private SingletonDemo() { } public static synchronized SingletonDemo getInstance() { if (instance == null) { instance = new SingletonDemo(); } return instance; } }
Or (I prefer this last one, it is more simple and easy to understand):
public class Singleton { private static final Singleton INSTANCE = new Singleton(); private Singleton() {} public static Singleton getInstance() { return INSTANCE; } }
This method has a number of advantages:
- The instance is not constructed until the class is used.
- There is no need to
synchronize
thegetInstance()
method, meaning all threads will see the same instance and no (expensive) locking is required. - The
final
keyword means that the instance cannot be redefined, ensuring that one (and only one) instance ever exists.
This is a very simple explanation, but helped me a lot. If you have some question, just write in the comments.
See you in the next post !