Singleton
The Singleton Design Pattern insures that only a single instance of a given object can exist.
If does this by making the class constructor private so that it [the singleton itself] has full control over when the class instance is created. In order to gain access to an instance of a class that implements the Singleton pattern, the developer must call a shared/static method of that Singleton class.
A VB example of a Singleton
Public Class SingletonSample
'shared members
Private Shared _instance As New SingletonSample
Public Shared Function Instance() As SingletonSample
Return _instance
End Function
'instance members
Private Sub New()
'public instantiation disallowed
End Sub
'other instance members
'...
End Class
A C# example of a Singleton
public class SingletonSample
{
//shared members
private static SingletonSample _instance = new SingletonSample();
public static SingletonSample Instance()
{
return _instance;
}
//instance members
private SingletonSample()
{
//public instantiation disallowed
}
//other instance members
//...
}
With the Singleton Design Pattern in place, the developer can easily access that single object instance without needing to worry about inadvertently creating multiple instances.
VB - Dim mySingleton As SingletonSample = SingletonSample.Instance
C# - SingletonSample mySingleton = SingletonSample.Instance();
Revision number 5, Saturday, February 16, 2008 3:21:11 PM by
This is not the most up to date version of this article. The most recent version can be found here.
You must Login to comment.
|
Fri, Mar 28, 2008 8:25 AM
by kulanthaivelu
|
Good Article. Now I got basic idea about singleton pattern. Thanks
|
|
Fri, Apr 11, 2008 1:40 AM
by shariff
|
cool!!!, thanks for the info, really helps me to understand SINGLETON.
|
|
Fri, Jun 13, 2008 4:34 PM
by dragthor
|
Is this thread safe?
|
|
Sun, Jun 15, 2008 7:46 PM
by mbanavige
|
since the singleton is created via a static initializer, its creation is thread-safe.
|
|
Fri, Aug 8, 2008 4:39 AM
by ojosdegris
|
sorry, have you looked at this, before writing this article? http://msdn.microsoft.com/en-us/library/ms954629.aspx sealed class Singleton { private Singleton() {} public static readonly Singleton Instance = new Singleton();
} i think it's better way to implement singleton in C#
|