Singleton class is a class whose only one object can be created at a
time
Singleton provides a global, single instance
by:
· Making the class create a single instance of
itself.
· Allowing other objects to access this
instance through a class method that returns a reference to the instance. A
class method is globally accessible.
· Declaring the class constructor as private so
that no other object can create a new instance.
Singleton results in the following benefits
and liabilities:
Benefits
· Instance
control. Singleton prevents other objects from
instantiating their own copies of the Singleton 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.
Liabilities
Liabilities
· Overhead. Although the amount is minuscule, there is some
overhead involved in checking whether an instance of the class already exists
every time an object requests a reference. This problem can be overcome by
using static initialization as described in Implementing Singleton in C#.
· Possible
development confusion. When using a
singleton object (especially one defined in a class library), developers must
remember that they cannot use the new keyword to instantiate the object.
Because application developers may not have access to the library source code,
they may be surprised to find that they cannot instantiate this class directly.
· Object
lifetime. Singleton does not address the issue of
deleting the single object. In languages that provide memory management (for
example, languages based on the .NET Framework), only the Singleton class could cause the instance to be
deallocated because it holds a private reference to the instance. In languages,
such as C++, other classes could delete the object instance, but doing so would
lead to a dangling reference inside the Singleton class.
No comments:
Post a Comment