Singleton is a class which has only one instance in whole
application. This design pattern suggests that at any time there can only be
one instance of a Singleton class object created by the JVM.
There are many classes in JDK which is implemented using
Singleton pattern like java.lang.Runtime which provides getRuntime() method to
get access of it and used to get free memory
and total memory in Java.
When to use Singleton?
- Singleton pattern used when we want to allow only a single instance of a class can be created inside our application. Using this pattern ensures that a class only have a single instance by protecting the class creation process, by setting the class constructor into private access modifier.For example, you can use it to create a connection pool. It’s not wise to create a new connection every time a program needs to write something to a database; instead, a connection or a set of connections that are already a pool can be instantiated using the Singleton pattern.
- Ensure that only one instance of a class is created
- Provide a global point of access to the object
- Allow multiple instances in the future without affecting a singleton class's clients