Singleton
Last updated
Last updated
Singleton is a creational design pattern that lets you ensure that a class has only one instance, while providing a global access point to this instance.
The Singleton design pattern ensures that a class has only one instance and provides a global point of access to that instance.
In this example:
The Singleton
class has a private static property instance
to hold the single instance of the class.
The constructor checks if an instance already exists. If it does not, it creates one and assigns it to Singleton.instance
.
If an instance already exists, it returns the existing instance.
The someMethod
is just a placeholder method to demonstrate usage.
When you create multiple instances of Singleton
, they all refer to the same instance.
Thus, only one instance of the Singleton
class exists throughout the application.