Introduction to Singleton
I'll start my article with one popular non-software example for Singleton.
Non-software Example
The office of the President of the United States is a Singleton. The United States Constitution specifies the means by which a president is elected, limits the term of office, and defines the order of succession. As a result, there can be at most one active president at any given time. Regardless of the personal identity of the active president, the title, "The President of the United States" is a global point of access that identifies the person in the office. [Michael Duell, "Non-software examples of software design patterns", Object Magazine, Jul 97, p54]
So sometimes in software engineering we need to have only one instance of a class which can coordinate the behaviour of our object. For example: OS should have only one Window Manager, our application should have only one mouse pointer, etc. Singleton is a class which we can use in such situations. It is very popular pattern in OOP. Its access modifier is sealed so we can't have is-a relationship i.e Singleton class cannot be inherited. Its constructor's access modifier is private i.e we can't create new instances. The main question is, how we access to Singleton class. We must have a private field that will hold our only instance, and a static method GetInstance() that returns our only instance. It is possible to use a property instead of method, too.
sealed class SingletonClass
{
private static SingletonClass myInstance = null;
private SingletonClass(){}
public static SingletonClass GetInstance()
{
if ( myInstance == null )
myInstance = new SingletonClass();
return myInstance;
}
}
The singleton pattern must be carefully constructed in multi-threaded applications. If two threads are to execute the creation method at the same time when a singleton does not yet exist, they both must check for an instance of the singleton and then only one should create the new one. If the programming language has concurrent processing capabilities the method should be constructed to execute as a mutually exclusive operation. Let's make our GetInstance() method thread safe.
We can achieve that by simply adding the lock keyword. That approach is known as Double-Check Lock with method
public static SingletonClass GetInstance()
{
if (myInstance == null)
lock( typeof(SingletonClass) )
{
if ( myInstance == null )
myInstance = new SingletonClass();
}
return myInstance;
}
We can use a property instead of method.
public static SingletonClass Instance
{
get
{
if (myInstance == null)
lock (typeof(SingletonClass))
{
if (myInstance == null)
myInstance = new SingletonClass();
}
return myInstance;
}
Bachelor of Computer Systems and Technologies, Technical University.
WinForms Developer since 2006.