Ensuring only one instance with the singleton pattern
A singleton object provides transparent and global access to its instance and ensures that only one instance is present. The singleton pattern was identified very early by industry requirements and is mentioned in the GoF’s book.
Motivation
A client or application wants to ensure that only one instance is present at runtime. An application may require multiple object instances that all use one unique resource. This fact introduces instability because any of these objects can access such a resource. A singleton guarantees only one instance that provides a global access point to all clients within the desired scope of the running JVM.
Finding it in the JDK
The best example of using a singleton is a running Java application, or more precisely, the runtime. It is found in the Runtime
class and its method, getRuntime
, resides in the java.lang
package of the java.base
module. The method returns an object associated...