The singleton pattern is a design pattern by which we cannot create more than one instance of the class.
It controls the object creation. It guarantees that at any given point of time only 1 object is present. In other words, it ensure a class only has one instance, and provide a global point of acces to it. |
Name: Singleton
Context: In some situations, a certain type of data needs to be available to all other objects in the application. In most cases, this type of data is also unique in the system. For example, a user interface can have only one mouse pointer that all applications must access.
Problem: Sometimes we want just a single instance of a class to exist in the system. We need to have that one instance easily accessible. And we want to ensure that additional instances of the class can not be created.
Solution: Making the class create a single instance of itself.
Declaring the class constructor as private so that no other object can create a new instance.
Structure:
Implementation: The singleton pattern is implemented by creating a class with a method that creates a new instance of the class if one does not exist. If an instance already exists, it simply returns a reference to that object. To make sure that the object cannot be instantiated any other way, the constructor is made private and parameterless.Note that the singleton instance is only created when needed.This is called lazy instantiation.
Benefits:
Instance control. Singleton prevents other objects from instantiating their own copies of the object, ensuring that all objects access the single instance.
Flexibility. Because the class controls the instantiation process, the class has the flexibility to change the instantiation process.
No comments:
Post a Comment